【发布时间】:2020-11-17 04:25:14
【问题描述】:
def dfs(node, target: int, path: List[int]):
if isLeaf(node):
if target - node.val == 0:
result.append(path[:] + [node.val])
return
if target < 0:
return
if node.left:
dfs(node.left, target - node.val, path[:] + [node.val])
if node.right:
dfs(node.right, target - node.val, path[:] + [node.val])
在上述方法中,如果我使用 "path[:] + [node.val]" 我将在结果中得到一个列表列表 ([[1,2,3,4],[1,2, 3,5]])。但是如果我使用“path.append(node.val)”而不是“path[:] + [node.val]”,我会得到列表的空列表([[],[]])。那么如果我们使用递归,我们应该传递新构造的列表的新副本吗?
【问题讨论】:
-
旁注:
res[:]+[value]完全等同于res + [value],除了它毫无意义地复制(可能很大)res。+已经在执行浅拷贝了,所以使用[:]显式地进行浅拷贝只是浪费。
标签: python-3.x list recursion