题目描述:

题目解答:
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> outcome=new ArrayList<>();
List<Integer> currentList=new ArrayList<>();
searchSet(candidates,target,0,outcome,currentList);
return outcome;
}
public void searchSet(int[] candidates,int target,int currentIndex,List<List<Integer>> outcome,List<Integer> currentList){
if(target==0){
outcome.add(new ArrayList<Integer>(currentList));
}else if(target>0){
for(int i=currentIndex;i<candidates.length;i++){
//如果出现有数字和前面的一样就跳过,因为在下面的迭代中已经完成添加了,为了防止重复
if(i>currentIndex&&candidates[i]==candidates[i-1]){
continue;
}
currentList.add(candidates[i]);
searchSet(candidates,target-candidates[i],i+1,outcome,currentList);
currentList.remove(currentList.size()-1);
}
}
}
}
运行结果:
