给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
思路:
1.先对数组排序,
2.分为三组情况
①sum==target
加入到组合就行
②sum<target
继续递归调用
③sum>target
停止
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);//先将数组进行排序
ArrayList<Integer> temp = new ArrayList<Integer>();
ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
generate(0,candidates,temp,result,0,target);//初始化的成员方法
return result;
}
public void generate(int i,int[] candidates,ArrayList<Integer> temp,ArrayList<List<Integer>> result,int sum,int target){
for(int j = i; j< candidates.length;j++){
sum+=candidates[j];
if (sum == target){
temp.add(candidates[j]);
result.add(new ArrayList<Integer>(temp));
temp.remove(temp.size()-1);
break;
}
if(sum < target){
temp.add(candidates[j]);
// result.add(new ArrayList<Integer>(temp));
generate(j+1,candidates,temp,result,sum,target);
sum-=candidates[j];
temp.remove(temp.size()-1);
while( j < candidates.length-1 && candidates[j]==candidates[j+1]){
j++;
}
}
if(sum > target){
break;
}
}
}
}
如有疑问,请留言联系。