40. Combination Sum II

Backtracking

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
backtracking(candidates, target, 0, 0);
return result;
}

private void backtracking(int[] candidates, int target, int sum, int startIndex) {
if (sum > target) return;
if (sum == target) {
result.add(new ArrayList<>(path));
return;
}

for (int i = startIndex; i < candidates.length; i++) {
if (candidates[i] > target) break;
if (i > startIndex && candidates[i] == candidates[i - 1]) continue;
path.add(candidates[i]);
backtracking(candidates, target, sum + candidates[i], i + 1);
path.remove(path.size() - 1);
}
}
}

Remarks:

  1. First sort array (very important!), then check the neighbor (next) candidate to avoid duplicates.
  2. TC: $O(2^n*k)$ (k is the average length).
  3. Same idea as LeetCode 39.