剑指 Offer II 082. 含有重复元素集合的组合(40. 组合总和 II)
给定一个候选人编号的集合 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.com/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
分析
参考:https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0040.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8CII.md
集合中数字有重复,同一个组合中只能用一次,学习去重。
微观上看,去重的思想可以是:将回溯代表的整棵树的某一层已经选取过的重复元素不予选取,实现的重点在于 1、如何判断当层的元素已经被选取过了,以及 2、如何判断当前代码是否是对当层进行操作的。下面来分析,结合上面的链接进行消化:
① 以三部曲的方法为例,我们一般会构造一个循环来完成回溯的过程,整个回溯过程是循环套循环的,每一层循环即为树的一层,对于一层大的循环来说,进来的 index 可以看作是固定的,循环变量 i 是在增加的,如果 i 大于 index 说明目前在大的循环体里(同一树层),这样就找到了树层,对于树层中的重复元素进行判断的方法是:比较当前索引处的元素与前一索引处的元素是否相同即可(数组已经排过序),因为使用三部曲的方法时,我们选取元素是从前往后选取的,所以前面的索引先选取,已经选取过的就不需要再选取了,判断如果相同就进入下一个索引,如果不相同就从当前索引进入下一个循环。
② 以选/不选的方法为例(书中方法),假设 nums = {2, 2, 2},target = 4。思路是跳过所有当前索引位置数字的重复数字,首先对于索引 0 的 2,选择不保留,然后跳过后面所有值为 2 的数,最后得到一个空集合 [];接下来保留索引 0 的 2,对于索引 1 的 2,选择不保留,跳过后面全部的 2,最后得到集合 [2];接下来保留索引 1 的 2,对于索引 2 的 2,选择不保留,跳过后面所有的 2,最后得到集合 [2, 2];最后保留索引 2 的 2,得到的集合是 [2, 2, 2]。
题解(Java)
三部曲法:
class Solution {
List<List<Integer>> ans = new LinkedList<>();
List<Integer> record = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
helper(candidates, target, 0, 0);
return ans;
}
private void helper(int[] candidates, int target, int sum, int index) {
if (sum == target) {
ans.add(new LinkedList<>(record));
return;
}
for (int i = index; i < candidates.length && sum + candidates[i] <= target; i++) {
if (i > index && candidates[i] == candidates[i - 1]) {
continue;
}
sum += candidates[i];
record.add(candidates[i]);
helper(candidates, target, sum, i + 1);
sum -= candidates[i];
record.remove(record.size() - 1);
}
}
}
选/不选法:
class Solution {
private List<List<Integer>> ans = new LinkedList<>();
private LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
helper(candidates, target, 0);
return ans;
}
private void helper(int[] candidates, int target, int index) {
if (target == 0) {
ans.add(new LinkedList<Integer>(path));
} else if (index < candidates.length && target - candidates[index] >= 0) {
int next = index;
while (next < candidates.length && candidates[next] == candidates[index]) {
next++;
}
helper(candidates, target, next);
path.add(candidates[index]);
helper(candidates, target - candidates[index], index + 1);
path.removeLast();
}
}
}