[英]Python - append list to other list?
Leetcode 113 - 路径总和 II
给定二叉树的根和 integer targetSum,返回所有从根到叶的路径,其中每个路径的总和等于 targetSum。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
if not root: return []
res = []
def dfs(node, total = 0, path = []):
if not node: return
path.append(node.val)
total += node.val
if not node.left and not node.right and total == targetSum:
res.append(list(path))
else:
dfs(node.left, total, path)
dfs(node.right, total, path)
total -= path.pop()
dfs(root)
return res
为什么我们必须使用res.append(list(path))
而不是res.append(path)
?
如果我们只将 append path
放入 res 中,则只会将 append 的空列表放入res
中。
这是一个微妙的 Python 问题。 当您使用这样的默认参数(在def dfs
行中)时,它会在定义时捕获默认的 object。 因此,每次 function 运行时, path
都会设置为相同的空列表。 如果您更改该列表,则引用它的每个人都会看到更改。 我相信他们使用 list(path) 来制作该列表的副本,而不是存储到公共列表的链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.