Combination Sum
Difficulty: Medium
Given a list of distinct positive numbers (candidates) and a target, find every unique combination of candidates that adds up exactly to the target.
You can use a candidate any number of times. Combinations with the same numbers used the same number of times are the same, whatever the order, so list each one only once.
Examples
Input: candidates = [2, 3, 6, 7], target = 7
Output: [[2, 2, 3], [7]]
2 + 2 + 3 = 7, using the 2 twice. And 7 by itself also works.
Input: candidates = [2, 3, 5], target = 8
Output: [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
Three different ways to reach 8 using repeats of 2 and/or 3.
Input: candidates = [2], target = 1
Output: []
No combination of 2s can ever add up to 1.
Constraints
1 <= candidates.length <= 30
2 <= candidates[i] <= 40
All elements of candidates are distinct.
1 <= target <= 40
Approach
Build a combination one number at a time, deciding which candidate to add next. Repeats are allowed, so you can add the same one again. To avoid the same combination in a different order, only move forward through the candidates, never back.
The straightforward version tries every candidate at every step, stopping when the total matches the target (a valid combination) or exceeds it (a dead end). After trying a candidate, remove it before trying the next - the choose/explore/un-choose pattern of backtracking.
Sorting the candidates first makes it faster. Once adding a candidate would overshoot the target, every later (bigger) candidate would too, so you can stop that step instead of checking each one.
Solutions
Backtracking — Try Every Candidate
At each step, loop over candidates from the current index onward. Add one, recurse with the same index (so it can be reused) and a smaller remaining target, then remove it. Stop a path when the remaining target hits zero (success) or goes negative (dead end).
function combinationSum(candidates, target) {
const result = [];
const current = [];
function backtrack(start, remaining) {
if (remaining === 0) {
result.push([...current]);
return;
}
if (remaining < 0) {
return;
}
for (let i = start; i < candidates.length; i++) {
current.push(candidates[i]);
backtrack(i, remaining - candidates[i]); // i, not i + 1: reuse allowed
current.pop();
}
}
backtrack(0, target);
return result;
}Time: O(2^target) in the worst case · Space: O(target / min(candidates)) recursion depth, plus output storage
Optimal — Sort and Prune
Sort the candidates first. At each step, once a candidate would push the total past the target, stop - every later candidate is at least as large, so none of them can work.
function combinationSum(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; // every candidate after this is even bigger
current.push(sorted[i]);
backtrack(i, remaining - sorted[i]);
current.pop();
}
}
backtrack(0, target);
return result;
}Time: O(2^target) worst case, but far fewer branches explored in practice · Space: O(target / min(candidates)) recursion depth, plus a sorted copy of the input