[英]Python - append list to other list?
Leetcode 113 - Path Sum II Leetcode 113 - 路径总和 II
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where each path's sum equals targetSum.给定二叉树的根和 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
Why we have to use res.append(list(path))
rather than use res.append(path)
?为什么我们必须使用
res.append(list(path))
而不是res.append(path)
?
If we only append path
into res, it would only append empty list into res
.如果我们只将 append
path
放入 res 中,则只会将 append 的空列表放入res
中。
This is a subtle Python issue.这是一个微妙的 Python 问题。 When you use a default parameter like that (in the
def dfs
line), it captures that default object at definition time.当您使用这样的默认参数(在
def dfs
行中)时,它会在定义时捕获默认的 object。 So, every time that function runs, path
is set to the SAME empty list.因此,每次 function 运行时,
path
都会设置为相同的空列表。 If you change that list, everyone with a reference to it sees the change.如果您更改该列表,则引用它的每个人都会看到更改。 I believe they use list(path) to make a copy of that list, rather than store a link to the common list.
我相信他们使用 list(path) 来制作该列表的副本,而不是存储到公共列表的链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.