【发布时间】:2021-05-02 11:21:07
【问题描述】:
我有一个解决以下问题的方法:https://leetcode.com/problems/combinations/
List[List[int]]:
def backtrack(first = 1, curr = []):
# if the combination is done
if len(curr) == k:
output.append(curr[:])
for i in range(first, n + 1):
# add i into the current combination
curr.append(i)
# use next integers to complete the combination
backtrack(i + 1, curr)
# backtrack
curr.pop()
output = []
backtrack()
return output
我的问题是关于curr.pop() 为什么我们每次迭代都弹出curr 组合?不应该有一些条件,比如curr已经在输出中了吗?
另一个问题是递归调用backtrack(i+1, curr) - 当它被调用时,我是否正确地说'i+1' 代替了主函数中的'first'?
【问题讨论】:
-
在这段代码中,
append扮演push的角色。并且函数调用的工作完全相同无论它们是否是递归的。 -
curr.pop()正在删除列表中的最后一项,即i,因为它是使用curr.append(i)添加的。
标签: python recursion recursive-backtracking