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]]
![Snipaste_2024-07-22_22-06-41.png](https://cdn.acwing.com/media/article/image/2024/07/22/217732_a95e0cb248-Snipaste_2024-07-22_22-06-41.png)