Combination Sum II
Difficulty: Medium
Given a list of numbers (which may repeat) and a target, find every unique combination from the list that adds up exactly to the target.
Each number can be used only as many times as it appears (if 5 appears twice, a combination may use two 5s, not three). The answer must not contain the same combination twice.
Examples
Input: candidates = [10, 1, 2, 7, 6, 1, 5], target = 8
Output: [[1,1,6], [1,2,5], [1,7], [2,6]]
The two 1s in the input let [1,1,6] use both of them, but each combination is only listed once even though there are two different 1s to pick from.
Input: candidates = [2, 5, 2, 1, 2], target = 5
Output: [[1,2,2], [5]]
There are three 2s available, so [1,2,2] can use two of them - but it's still only listed once.
Constraints
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
Approach
This is like Combination Sum, except each position can be used only once, and repeated values need care so no combination appears twice.
"Use each position once" is easy: after using candidates[i], the next pick comes from i + 1 onward.
Duplicate values are trickier. The brute-force fix searches freely and removes repeat combinations afterward, as in Subsets II. The cleaner fix sorts the candidates, and when you skip a value at a step, also skips any later equal value at that step - so no two branches build the same combination.
Solutions
Brute Force — Backtrack Then De-duplicate
Move forward through the unsorted list, using each position at most once, and collect every combination that sums to the target. Duplicate values can build the same combination more than once, so afterward key each result on its sorted, comma-joined values to remove repeats.
function combinationSum2(candidates, target) {
const all = [];
const current = [];
function backtrack(start, remaining) {
if (remaining === 0) {
all.push([...current]);
return;
}
if (remaining < 0) return;
for (let i = start; i < candidates.length; i++) {
current.push(candidates[i]);
backtrack(i + 1, remaining - candidates[i]);
current.pop();
}
}
backtrack(0, target);
const seen = new Set();
const result = [];
for (const combo of all) {
const key = [...combo].sort((a, b) => a - b).join(",");
if (!seen.has(key)) {
seen.add(key);
result.push(combo);
}
}
return result;
}Time: O(2^n * n) to generate combinations, plus O(2^n * n) to key and de-duplicate them · Space: O(2^n * n) for the raw combinations and the de-duplication set
Optimal — Sort and Skip Duplicate Branches
Sort the candidates so equal values are neighbors. Move forward through the list (never reusing a position), and at each step skip a candidate equal to the one before it - trying only the first equal value covers every combination with that value. Stop a branch when the remaining target hits zero or a candidate would overshoot it.
function combinationSum2(candidates, target) {
const sorted = [...candidates].sort((a, b) => a - b);
const result = [];
const current = [];
function backtrack(start, remaining) {
if (remaining === 0) {
result.push([...current]);
return;
}
for (let i = start; i < sorted.length; i++) {
if (sorted[i] > remaining) break; // sorted, so nothing further can work either
if (i > start && sorted[i] === sorted[i - 1]) continue; // skip duplicate at this level
current.push(sorted[i]);
backtrack(i + 1, remaining - sorted[i]); // i + 1: this position can't be reused
current.pop();
}
}
backtrack(0, target);
return result;
}Time: O(2^n) worst case · Space: O(n) recursion depth, plus a sorted copy of the input