LeetCode第40题思悟——组合总数II(combination-sum-ii)
知识点预告
- 数组的排序处理;
- 分治思想的应用;
- 递归结果的返回处理;
题目要求
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
示例 2:输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
]来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的思路
这道题和上道题是相同类型的,只是增加了每个数字只能使用一遍,于是我们需要增加一个跳跃操作;
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
if(candidates.length==0){
return new ArrayList<>();
}
Arrays.sort(candidates);
return combinationSum(candidates,target,0);
}
private static boolean contains(int[] candidates,int start,int end,int target){
int left=start,right=end;
int middle;
while(left<=right){
middle=(left+right)/2;
if(candidates[middle]<target){
left=middle+1;
}else if(candidates[middle]>target){
right=middle-1;
}else{
return true;
}
}
return false;
}
private static List<List<Integer>> combinationSum(int[] candidates,int target,int start){
List<List<Integer>> result=new ArrayList<>();
List<List<Integer>> subResult;
int index=start;
int nextIndex=index+1;
int headValue=candidates[index];
int realTarget=target-candidates[index];
List<Integer> item;
if(contains(candidates,start,candidates.length-1,target)){
item=new ArrayList<>();
item.add(target);
result.add(item);
}
if(nextIndex<candidates.length) {
while (headValue <= realTarget) {
subResult = combinationSum(candidates, realTarget, nextIndex);
if (subResult.size() != 0) {
for (List<Integer> answer : subResult) {
answer.add(headValue);
result.add(answer);
}
}
while(index<candidates.length&&candidates[index]==headValue){
index++;
}
nextIndex=index+1;
if (nextIndex < candidates.length) {
headValue = candidates[index];
realTarget = target - headValue;
} else {
break;
}
}
}
return result;
}
优秀解法
List<List<Integer>> result = new ArrayList<>();
// c:给定数组
// index:当前从index开始
// t:目标和
// l:结果
void f(int[] c,int index,int t,List<Integer> l){
if (t == 0){
// 找到了一个组合方式
result.add(new ArrayList<>(l));
return;
}
for (int i = index; i < c.length && c[i] <= t; i++){
if (i != index && c[i] == c[i - 1]) continue;
// 下一个位置
l.add(c[i]);
f(c,i + 1,t - c[i],l);
l.remove(l.size() - 1);
}
}
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
if (candidates == null || candidates.length == 0) return result;
Arrays.sort(candidates);
f(candidates,0,target,new ArrayList<>());
return result;
}
差异分析
因为题目要求的变化,所以都是需要在上一题的基础上加上跳跃操作;另外,对于题目中说的,“candidates 中的每个数字在每个组合中只能使用一次”,那么candidates中是否存在重复数字?比如,出现2个1,那么1在结果中是允许出现2次还是1次呢?从通过的提交来看,应该还是只能出现1次;
至于这个问题,如果在面试中,还是需要确定一下的,否则直接index++不就好啦;
知识点小结
- 数组的排序处理;
- 分治思想的应用;
- 递归结果的返回处理;