击败了99%的男人!!
题目如下
代码如下
public List<List<Integer>> combinationSum2(int[] candidates, int target){
List<List<Integer>> list1=new ArrayList<>();
List<Integer> list2=new ArrayList<>();
Arrays.sort(candidates);
dfs(candidates,target,list1,list2,0);
return list1;
}
public void dfs(int[] candidates,int target,List<List<Integer>> list1,List<Integer> list2,int index){
if(target==0){
//if(!list1.contains(new ArrayList<>(list2)))
list1.add(new ArrayList<>(list2));
return;
}
if(index==candidates.length) return;
if(target>0){
list2.add(candidates[index]);
if(target-candidates[index]>=0) dfs(candidates,target-candidates[index],list1,list2,index+1);
list2.remove(list2.size()-1);
if(target-candidates[index]>=0){
while(index+1<candidates.length&&candidates[index]==candidates[index+1]){
index++;
}
dfs(candidates,target,list1,list2,index+1);
}
}
}