回溯算法的比较基础的问题
比39多了去重,剪枝操作
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result=new ArrayList<>();
Arrays.sort(candidates);
combination(target,new ArrayList<Integer>(),candidates,0,result);
return result;
}
public static void combination(int sum,List<Integer>temp,int[]candidates,int start,
List<List<Integer>> result){
if(sum==0){
result.add(new ArrayList<>(temp));
return;
}
for(int i=start;i<candidates.length;i++){
if(sum-candidates[i]<0)break;
if(i>start&&candidates[i]==candidates[i-1])continue;
temp.add(candidates[i]);
combination(sum-candidates[i],temp,candidates,i+1,result);
temp.remove(temp.size()-1);
}
}
}