40. Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C 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.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
解法
在leetcode39. Combination Sum I的基础上改动了两处地方:
backtrack(ret, temp, candidates, remain candidates[i], i + 1); //不包含本次元素
if (i > start && candidates[i] == candidates[i- 1]) continue; // 去除重复的list,如[[1, 7], [1, 7]],i>start为了避免数组越界,如0-1=-1
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> ret = new ArrayList<>();
if (candidates == null || candidates.length == 0 || target <= 0) {
return ret;
}
Arrays.sort(candidates);
backtrack(ret, new ArrayList<Integer>(), candidates, target, 0);
return ret;
}
private void backtrack(List<List<Integer>> ret, List<Integer> temp, int[] candidates, int remain, int start) {
if (remain == 0) {
ret.add(new ArrayList<Integer>(temp));
} else if (remain < 0) {
return;
}
for (int i = start; i < candidates.length; i++) {
if (i > start && candidates[i] == candidates[i- 1]) continue;
temp.add(candidates[i]);
backtrack(ret, temp, candidates, remain - candidates[i], i + 1);
temp.remove(temp.size() - 1);
}
}
}