class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
List<Integer> tmp = new ArrayList<>();
find(candidates, target, 0, tmp, res);
return res;
}
void find(int[] candidates, int target, int i, List<Integer> tmp, List<List<Integer>> res){
if(target < 0) return;
if(target == 0){
res.add(new ArrayList<>(tmp));
// res.add(tmp); 为啥子不对
return;
}
for(int j = i; j < candidates.length && target >= candidates[j]; j++){
tmp.add(candidates[j]);
find(candidates, target-candidates[j], j, tmp, res);
tmp.remove(tmp.size() - 1);
}
}
}
public static void main(String[] args) {
List<List<Integer>> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
for (int i = 0; i < 5; i++) {
list2.add(i);
}
list1.add(list2);
System.out.println("list1 : " + list1);
System.out.println("list2 : " + list2);
list2.remove(list2.size() - 1);
System.out.println("list1 : " + list1);
System.out.println("list2 : " + list2);
/**
* list1 里面存的是 list2 的引用, 当list2引用的对象发生变化时, list1也会随之改变
*/
}
output
list1 : [[0, 1, 2, 3, 4]]
list2 : [0, 1, 2, 3, 4]
list1 : [[0, 1, 2, 3]]
list2 : [0, 1, 2, 3]