简略要点(具体见前几篇回溯带重题)
1、回溯
2、带重
3、避免超时,应及时剪枝
详细见注释
class Solution {
List<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> track = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
if(candidates.length == 0){
return res;
}
//带重,排序
Arrays.sort(candidates);
int sum = 0;
backtrack(candidates,target,0,sum);
return res;
}
public void backtrack(int[] candidates,int target,int start,int sum){
//base case
if(sum == target){
res.add(new LinkedList<>(track));
return;
}
//避免超时!!
if(sum>target){
return;
}
for(int i = start; i<candidates.length;i++){
//带重
if(i>start&&candidates[i] == candidates[i-1]){
continue;
}
//选择
sum += candidates[i];
track.add(candidates[i]);
//递归回溯
backtrack(candidates,target,i+1,sum);
//撤销
track.removeLast();
sum -= candidates[i];
}
}
}