题目
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]提示:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
和39的区别是,39无重复数字,每个数可以用多次;这个题有重复数字,但每个数只能用一次。
大致框架和39基本一样,首先不同的是,递归下次的循环开始为i+1而不是i。
光改掉这里还不够,发现会陈胜重复结果,比如输入[1,1,2,5]和8,不去重的话会有两个[1,2,5],因此需要去重。
这里去重的思想和全排列II有些相似,同一层(同一个循环)只考虑出现多次的数中的第一个,比如还是前面的例子,第一个for循环中,考虑了第一个1就不需要再考虑第二个1了,因为后者一定不会再产生使用第一个1无法产生的结果。因此,在一个for循环中,如果当前数和前面的数相同,就跳过,当然前提是将数组排好序。
关于去重,「这个」评论解释的不错,可以看一下。
代码
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
int n = candidates.length;
// 排序一是为了去重,二是为了剪枝
Arrays.sort(candidates);
dfs(candidates, target, n, 0, 0, new ArrayDeque<>(), ans);
return ans;
}
private void dfs(int[] candidates, int target, int n, int sum, int start, Deque<Integer> path, List<List<Integer>> ans) {
if (sum > target) {
return;
}
if (sum == target) {
ans.add(new ArrayList<>(path));
return;
}
for (int i = start; i < n; i++) {
// 剪枝
if (sum + candidates[i] > target) {
break;
}
// 去重,思想类似全排列II中的思想
if (i > start && candidates[i] == candidates[i - 1]) {
continue;
}
path.offerLast(candidates[i]);
dfs(candidates, target, n, sum + candidates[i], i + 1, path, ans);
path.pollLast();
}
}
}