从集合中取n个数和为target,数字可能有重复,每个数字只能选一次,这道题目需要注意candidates[] 数组中的元素是会有重复的,所以答案里面会出现重复的解,需要在求解过程中对相同的数字不再进行深度搜索即可。
public class Solution {
public List<List<Integer>> ans = new ArrayList<>();
public List<Integer> tmp = new ArrayList<>();
//index 表示当前数组下标 需要考虑重复情况
public void robot(int index,int sum,int[] candidates, int target,List<Integer> tmp){
//边界条件
if(sum == target){
ans.add(new ArrayList<>(tmp));
return ;
}else if(sum > target || index >candidates.length) return;
int prev =-1;
for(int i=index;i<candidates.length;i++){
if(candidates[i] != prev){ //不重复的情况进行搜索
//取第i位置上的数
tmp.add(candidates[i]);
robot(i+1,sum+candidates[i],candidates,target,tmp);
//不取第i位置上的数
tmp.remove(tmp.size()-1);
prev = candidates[i];
}
}
}
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
ans.clear();
Arrays.sort(candidates);//排序
robot(0,0,candidates,target,tmp);
return ans;
}
}