场景:
今天在做力扣39. 组合总和的时候,调试半天不得其解,室友一语中的。
题目如下:
public static List<List<Integer>> res = new ArrayList<>();
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
trackBack(candidates,target,new ArrayList<Integer>(),0);
return res;
}
public static void trackBack(int[] candidates, int target, ArrayList<Integer> integers, int i) {
if(target < 0) return;
if(target == 0){
res.add(new ArrayList<>(integers));
/**
res.add(integers);
**/
return;
}
for (int start = i; start < candidates.length; start++) {
integers.add(candidates[start]);
trackBack(candidates,target - candidates[start],integers,start);
integers.remove(new Integer(candidates[start]));
}
}
代码块为:res.add(integers);
结果为:[[], []]
代码块为:res.add(new ArrayList<>(integers));
结果为:[[2, 2, 3], [7]]
总结:
- ArrayList integers作为参数传递时,传递的是此对象所在的地址;
- 我在回溯修改integers时,修改的都是所在此地址中的实际数据值;
- 所以如果是第一种:最后结果全是空,因为运行结束,integers中都被删完了;
- 第二种是每次add时,都重新创建对象,这样才能保存有效值。