dfs
的两种不同架构
第一种
def dfs(u):
res.append(pt[:])
if u == len(nums):
return None
for i in range(len(nums)):
pt.append(nums[i])
dfs(u + 1)
pt.pop()
res = []
pt = []
nums = list(map(int, input().split()))
dfs(0)
print(res)
# 结果
1 2 3
[[], [1], [1, 1], [1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, 3], [1, 3, 1], [1, 3, 2], [1, 3, 3], [2], [2, 1], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 3], [2, 3, 1], [2, 3, 2], [2, 3, 3], [3], [3, 1], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 2], [3, 2, 1], [3, 2, 2], [3, 2, 3], [3, 3], [3, 3, 1], [3, 3, 2], [3, 3, 3]]
第二种
def dfs(u):
res.append(pt[:])
if u == len(nums):
return None
for i in range(u, len(nums)):
pt.append(nums[i])
dfs(i + 1)
pt.pop()
res = []
pt = []
nums = list(map(int, input().split()))
dfs(0)
print(res)
# 结果
1 2 3
[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]