又写了超时版:
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> curRes = new ArrayList<>();
Arrays.sort(candidates);
comb(0,curRes,res,candidates,target);
return res;
}
public void comb(int idx,List<Integer> curRes,List<List<Integer>> res, int[] candidates, int target){
for(int i=idx;i<candidates.length;i++){
if(target==candidates[i]){
curRes.add(candidates[i]);
List<Integer> cr = new ArrayList<>(curRes);
if(!res.contains(cr)){
res.add(cr);
}
curRes.remove(curRes.size() - 1);
}else if(target-candidates[i]>0){
curRes.add(candidates[i]);
comb(i+1,curRes,res,candidates,target-candidates[i]);
if(curRes.size()>0){
curRes.remove(curRes.size() - 1);
}
}else{
if(curRes.size()>0){
return;
}
}
}
}
}