class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
List<Integer> list = new ArrayList<>();
helper(res, list, root, sum);
return res;
}
public void helper(List<List<Integer>> res, List<Integer> list, TreeNode root, int sum){
list.add(root.val);
if(root.left == null && root.right == null){
if(root.val == sum)
res.add(new ArrayList<>(list));
}
if(root.left != null)
helper(res, list, root.left, sum-root.val);
if(root.right != null)
helper(res, list, root.right, sum-root.val);
list.remove(list.size()-1);
}
}
我正在研究Leetcode 113. Path Sum II。这与问题本身无关。我想知道为什么我必须在第13行编写res.add(new ArrayList<>(list));
而不是直接编写res.add(list);
。
发布于 2018-08-13 23:24:41
编写new ArrayList<>(list)
将创建一个新列表,其中包含list
中的所有元素。这是必需的,因为在调用list.remove(list.size()-1);
的函数结束时,需要修改list
变量。
如果要直接在res
中添加list
,remove
调用也会修改res
。
另一个相关的例子:
class MyClass {
public int modify = 5;
}
class Test {
public static void myFunction() {
MyClass object = new MyClass();
System.out.println(object.modify); // prints 5.
ArrayList<MyClass> myList = new ArrayList<>();
myList.add(object);
object.modify = 800;
for(MyClass item : myList) {
System.out.println(item.modify); // prints 800.
}
}
}
发布于 2018-08-13 23:25:16
new ArrayList<>(list)
将创建list
的副本,这将确保元素存储到res
中。
否则,在list.remove(list.size()-1)
之后,res
中的元素将被删除。
https://stackoverflow.com/questions/51825663
复制相似问题