40 Combination Sum II

1. Question

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 target8, A solution set is:
1
[
2
[1, 7],
3
[1, 2, 5],
4
[2, 6],
5
[1, 1, 6]
6
]
Copied!

2. Implementation

(1) Backtracking
1
class Solution {
2
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
3
List<List<Integer>> res = new ArrayList<>();
4
List<Integer> combinations = new ArrayList<>();
5
Arrays.sort(candidates);
6
getCombinations(candidates, 0, 0, target, combinations, res);
7
return res;
8
}
9
10
public void getCombinations(int[] candidates, int index, int sum, int target, List<Integer> combinations, List<List<Integer>> res) {
11
if (sum > target) {
12
return;
13
}
14
15
if (sum == target) {
16
res.add(new ArrayList<>(combinations));
17
return;
18
}
19
20
for (int i = index; i < candidates.length; i++) {
21
if (i > index && candidates[i - 1] == candidates[i]) {
22
continue;
23
}
24
25
combinations.add(candidates[i]);
26
getCombinations(candidates, i + 1, sum + candidates[i], target, combinations, res);
27
combinations.remove(combinations.size() - 1);
28
}
29
}
30
}
Copied!

3. Time & Space Complexity

Backtracking: 时间复杂度O(2^n), 空间复杂度O(2^n)