Combination Sum II (M)
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]
题意
给一串数,找出所有和等于目标值的组合,每个数字只能使用一次,且解集中不许有重复的组合。
思路
与 39. Combination Sum 方法基本一样,使用回溯法,只是要求数字只能使用一次且不许有重复组合,所以只要加一行对重复元素的判断和修改递归参数即可。
代码实现
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
// 先排序方便处理
Arrays.sort(candidates);
List<List<Integer>> ans = new ArrayList<>();
solve(candidates, target, 0, 0, new ArrayList<>(), ans);
return ans;
}
private boolean solve(int[] candidates, int target, int index, int sum, List<Integer> list, List<List<Integer>> ans) {
if (sum > target) {
return false;
}
if (sum == target) {
ans.add(new ArrayList<>(list));
return false;
}
for (int i = index; i < candidates.length; i++) {
// 相同数字在同一递归深度只插入一次,以免出现重复组合的情况
if (i > index && candidates[i] == candidates[i - 1]) {
continue;
}
list.add(candidates[i]);
// 每个数字只使用一次,所以递归时从下一个元素开始,index=i+1
boolean flag = solve(candidates, target, i + 1, sum + candidates[i], list, ans);
list.remove(list.size() - 1);
// 如果递归返回值为false,说明刚刚加入的数已经使整个序列的和达到了最大限值
// 不用再继续加入更大的值,可以直接跳出。
if (!flag) {
break;
}
}
return true;
}
}