【发布时间】:2017-12-26 06:00:20
【问题描述】:
我正在尝试使用 DFS 实现“子集”算法。我发现以下两个程序都有效:
def DFS(nums, begin, path, res):
res.append(path[:])
for i in range(begin, len(nums)):
path.append(nums[i])
DFS(nums, i + 1, path, res)
path.pop()
def DFS_2(nums, begin, path, res):
if begin == len(nums):
res.append(path[:])
return
path.append(nums[begin])
DFS_2(nums, begin + 1, path, res) #choose the current element
path.pop()
DFS_2(nums, begin + 1, path, res) #not choose the current element
测试代码是:
nums = [i for i in range(1, 4)]
res = []
path = []
DFS_2(nums, 0, path, res)
print(res)
res2 = []
DFS(nums, 0, path, res2)
print(res2)
输出是:
DFS_2:[[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]
DFS:[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
我可以理解DFS_2,因为在每次递归中,我有两个选择——选择当前元素或不选择当前元素。但是我很难理解函数DFS。如何理解函数DFS 中的for 循环?我的猜测是函数DFS_2中存在尾递归,这就是函数DFS和DFS_2相互等价的原因,但我不确定细节。
感谢任何提示。
【问题讨论】:
-
在不知道您在这些变量(nums、begin、path、res)中实际拥有什么的情况下,我们如何为您提供帮助?
-
添加了测试代码和输出
-
我的建议是你拿一张纸,画出正在发生的事情。到时候一切都会清楚得多。
标签: python algorithm recursion depth-first-search