Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
public List<List<Integer>> combinationSum(int[] nums, int target) {
//list里是list,list里是int
List<List<Integer>> list = new ArrayList<>();
//先排序
Arrays.sort(nums);
backtrack(list, new ArrayList<>(), nums, target, 0);
return list;
}
private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){
//没找到答案,返回
if(remain < 0) return;
//找到答案了,加入templist
else if(remain == 0) list.add(new ArrayList<>(tempList));
else{
for(int i = start; i < nums.length; i++){
tempList.add(nums[i]);
backtrack(list, tempList, nums, remain - nums[i], i); // not i + 1 because we can reuse same elements
//为什么要去除,懂了
tempList.remove(tempList.size() - 1);
}
}
}