题目描述
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]
]
算法
时间复杂度 我已经算不清楚了,感觉是O(2^n)
参考文献
Java 代码
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
int n = candidates.length;
if (n == 0 || target == 0) {
return res;
}
Arrays.sort(candidates);
dfs(candidates, target, 0, new ArrayList<Integer>());
return res;
}
private void dfs(int[] candidates, int target, int start, List<Integer> path) {
if (target < 0) {
return;
}
if (target == 0) {
res.add(new ArrayList<>(path));
return;
}
for (int i = start; i < candidates.length; i++) {
// 剪枝1,因为排序过,直接break, 后面不用管了
if (target < candidates[i]) {
break;
}
// 剪枝2,过滤重复解,注意i > start本次枚举的起点,如果出现1,2,2,2,5,6,9,10,需要去掉第2,3个2
if (i > start && candidates[i] == candidates[i - 1]) {
continue;
}
path.add(candidates[i]);
dfs(candidates, target - candidates[i], i + 1, path);
path.remove(path.size() - 1);
}
}
}