子集

子集 Python 算法

nums = list(map(int, input().split()))
n = len(nums)
res = []

def dfs(start, path):
    res.append(path.copy())

    for i in range(start, n):
        path.append(i)
        dfs(i + 1, path)
        path.pop()
dfs(0, [])
print(res)

全排列 Python 算法

# vis 法
nums = list(map(int, input().split()))
n = len(nums)
vis = [False] * n
res = []

def dfs(path:list[int]):
    if len(path) == n:
        res.append(path[:])
        return
    for i in range(n):
        if not vis[i]:
            vis[i] = True
            path.append(nums[i])
            dfs(path)
            vis[i] = False
            path.pop()
dfs([])
print(res)
# 交换法
def permute(nums):
    res = []
    
    def dfs(start):
        if start == len(nums):
            res.append(nums[:])
            return
        for i in range(start, len(nums)):
            nums[start], nums[i] = nums[i], nums[start]
            dfs(start + 1)
            nums[start], nums[i] = nums[i], nums[start]
    
    dfs(0)
    return res

print(permute([1, 2, 3]))