40.Combination Sum II
https://leetcode.com/problems/combination-sum-ii/
Last updated
https://leetcode.com/problems/combination-sum-ii/
Last updated
public List<List<Integer>> combinationSum2(int[] num, int target) {
List<List<Integer>> result=new ArrayList<>();
if(num==null || num.length==0){
return result;
}
List<Integer> path=new ArrayList<Integer>();
Arrays.sort(num);
dfs(num,0,target,path,result);
return result;
}
public void dfs(int[] num,int startindex,int target,List<Integer> path,List<List<Integer>> result){
if(target==0){
result.add(new ArrayList<Integer>(path));
}
for(int i=startindex;i<num.length;i++){
//这里必须先判断i不是startindex,否则会出现ArrayIndexOutOfBoundsException
if(i!=startindex && num[i]==num[i-1]){
continue;
}
if(target<num[i]){
break;
}
path.add(num[i]);
//这里要从i+1
dfs(num,i+1,target-num[i],path,result);
path.remove(path.size()-1);
}
}