Leecode 0040. Combination Sum II
40. Combination Sum II
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sum to target
.
Each number in candidates
may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Example 1:
1 | Input: candidates = [10,1,2,7,6,1,5], target = 8 |
Example 2:
1 | Input: candidates = [2,5,2,1,2], target = 5 |
题目大意
给定一个可能包含重复元素的整数数组 candidates
和一个目标整数 target
,找出所有不重复的组合,使得组合中数字的和等于 target
。数组中的每个数字只能使用一次,且解集不能包含重复的组合。
例如:
- 输入
candidates = [10,1,2,7,6,1,5], target = 8
,输出[[1,1,6],[1,2,5],[1,7],[2,6]]
- 输入
candidates = [2,5,2,1,2], target = 5
,输出[[1,2,2],[5]]
解题思路
核心思路是递归回溯 + 排序去重,在允许重复元素的数组中寻找符合条件的组合:
- 排序预处理:先对
candidates
排序,使相同元素相邻,为后续去重做准备。 - 递归回溯:
- 每次从当前位置开始选择数字(避免组合内元素重复使用);
- 选择数字后,目标和减去该数字,递归处理下一个位置(数字不能重复使用);
- 递归结束后回溯(移除最后选择的数字),尝试其他数字。
- 去重关键:
- 当遇到与前一个元素相同的数字时,若前一个元素未被选择,则跳过当前数字(避免重复组合)。
- 终止条件:
- 若剩余目标和为 0,将当前组合加入结果;
- 若剩余目标和小于 0,终止当前递归(剪枝)。
代码实现
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.