https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

为什么我把ans和path变成参数传递,反而是运行时间多3ms,占用内存只少100k?

构造函数:new ArrayList(al)把al的所有值复制到 new ArrayList()里,并且 new ArrayList()的值不会随着al的改变而改变。

al0.addAll(al):当al的值改变,al0的值也随之改变。

Collections.copy(des,res):我一直都不知道怎么用= =

 1     ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
 2     ArrayList<Integer> path = new ArrayList<>();
 3
 4     public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
 5         if (root == null) return ans;
 6         dfs(root, 0, target);
 7         return ans;
 8     }
 9
10     void dfs(TreeNode r, int now, int target) {
11         now += r.val;
12         if (now > target) return;
13         if (r.left == null && r.right == null && now != target) return;
14         if (r.left == null && r.right == null && now == target) {
15             path.add(r.val);
16             ans.add(new ArrayList<>(path));
17             path.remove(path.size() - 1);
18             return;
19         }
20         path.add(r.val);
21         if (r.left != null) dfs(r.left, now, target);
22         if (r.right != null) dfs(r.right, now, target);
23         path.remove(path.size() - 1);
24     }
02-01 03:28