Combination Sum II
Given a collection of candidate numbers candidates (which may contain duplicates) and a target number target, find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination.
Example 1
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: [[1,1,6],[1,2,5],[1,7],[2,6]]
Explanation: 1+1+6=8, 1+2+5=8, 1+7=8, 2+6=8.
Output: [[1,1,6],[1,2,5],[1,7],[2,6]]
Explanation: 1+1+6=8, 1+2+5=8, 1+7=8, 2+6=8.
Example 2
Input: candidates = [2,5,2,1,2], target = 5
Output: [[1,2,2],[5]]
Output: [[1,2,2],[5]]
Solution Approach
Sort the array first. The key difference from Combination Sum I is that each element can only be used once (recurse with i+1) and we must skip duplicates at the same tree level to avoid duplicate combinations.
- Sort candidates to bring duplicates adjacent and enable pruning.
- In the loop, skip if
i > start && candidates[i] == candidates[i-1]. - Recurse with
i+1(noti) since each element is used at most once. - Prune when
candidates[i] > remaining.
Java
import java.util.*;
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<>();
backtrack(candidates, target, 0, new ArrayList<>(), result);
return result;
}
private void backtrack(int[] candidates, int remaining,
int start, List<Integer> current,
List<List<Integer>> result) {
if (remaining == 0) {
result.add(new ArrayList<>(current));
return;
}
for (int i = start; i < candidates.length; i++) {
if (candidates[i] > remaining) break;
// Skip duplicates at the same depth level
if (i > start && candidates[i] == candidates[i - 1]) continue;
current.add(candidates[i]);
backtrack(candidates, remaining - candidates[i], i + 1, current, result);
current.remove(current.size() - 1);
}
}
}
Complexity Analysis:
Time complexity: O(2^n) in the worst case since each element is either included or excluded.
Space complexity: O(n) for the recursion stack.