Combination Sum
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given an array of distinct positive integers candidates and a target, return every unique combination of candidates that adds up to target. You may use the same candidate any number of times.
Understand the problem
- A combination is a group of numbers where order doesn't matter:
[2, 2, 3]and[3, 2, 2]are the same combination, so list it only once. - You can reuse a number as often as you like:
2 + 2 + 3 = 7uses2twice. - You need all the combinations, not just one, and not just how many.
- Return them in any order.
Example 1
Input: candidates = [2, 3, 6, 7], target = 7
Output: [[2, 2, 3], [7]]2 + 2 + 3 = 7 and 7 = 7. Nothing else adds up to exactly 7: for example 3 + 3 = 6 is one short, and 3 + 3 + 2 = 8 is one too many.
Example 2
Input: candidates = [2, 3, 5], target = 8
Output: [[2, 2, 2, 2], [2, 3, 3], [3, 5]]Example 3
Input: candidates = [2], target = 1
Output: []The only candidate is already bigger than the target.
Constraints
1 <= candidates.length <= 302 <= candidates[i] <= 40, all distinct1 <= target <= 40
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Build combinations one number at a time with recursion, only ever adding candidates at or after the last one used (so each combination is built in one order), and undo each choice after exploring it.
What is backtracking?
Backtracking is a way to try every possible sequence of choices, using recursion. You build an answer one choice at a time:
choose → path.push(x) add a number to the current combination
explore → recurse find everything that can follow it
undo → path.pop() remove it, so you can try the next optionThe "undo" step is what gives it its name: after exploring a choice, you back up and try a different one. One path array is reused for the whole search.
You can picture it as a tree of choices. Each branch adds one number; a branch stops when the remaining amount hits 0 (found one!) or would go below 0 (dead end).
The key insight: avoiding duplicates
If at every step you could pick any candidate, you'd find [2, 2, 3], [2, 3, 2] and [3, 2, 2]: the same combination three times.
The fix: build every combination in non-decreasing order of position. Pass a start index, and only try candidates from start onward:
- Recurse with the same
i(noti + 1), so the same number can be used again. - Never go back to a candidate before
i.
Then [2, 2, 3] can be built, but [3, 2, 2] can't (after choosing 3, going back to 2 isn't allowed).
A bonus speed-up: sort the candidates first. Then, as soon as one candidate is bigger than what's left, every later one is too, so you can stop the loop (break).
Step by step
candidates = [2, 3, 6, 7], target = 7:
| Path | Remaining | What happens |
|---|---|---|
[2] | 5 | keep going, from 2 onward |
[2, 2] | 3 | keep going |
[2, 2, 2] | 1 | every candidate is bigger than 1: dead end, undo |
[2, 2, 3] | 0 | found! record it, undo |
[2, 3] | 2 | only 3 and later allowed, all bigger than 2: dead end |
[3] | 4 | [3, 3] leaves 1: dead end. 6 > 4: stop |
[6] | 1 | dead end |
[7] | 0 | found! |
Result: [[2, 2, 3], [7]].
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: exponential. The number of combinations itself can be huge. Roughly, the search tree has depth up to
target / (smallest candidate)and branches up tonways at each level. - Memory: O(target / smallest candidate) for the recursion and the path (not counting the output).
That sounds bad, but it's expected: when a problem asks for all combinations, there can be exponentially many, and any solution has to list them.
Common mistakes
- Pushing
pathitself into the result. It's the same array you keep changing, so every entry ends up identical (and usually empty). Push a copy:[...path]. - Recursing with
i + 1. Then each number can only be used once, which is a different problem (Combination Sum II). - Starting the loop at 0 every time. That produces the same combination in different orders.
- Forgetting to undo (
path.pop()). The next branch then starts with leftover numbers.
Going deeper
This "choose, explore, undo" template solves a whole family of problems: Subsets, Permutations, Combination Sum II (each number once, with duplicates in the input), N-Queens and Sudoku. Only the choices and the "is this complete / is this a dead end" checks change.
Reference solution
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
export default function combinationSum(candidates, target) {
// Sorted, so we can stop as soon as a candidate is too big.
const sorted = [...candidates].sort((a, b) => a - b)
const result = []
const path = [] // the combination being built right now
// Only candidates from `start` onward may be added: each combination is built in one order.
function backtrack(start, remaining) {
if (remaining === 0) {
result.push([...path]) // found one: save a COPY (path keeps changing)
return
}
// Sorted: once a candidate is bigger than what's left, all later ones are too.
for (let i = start; i < sorted.length && sorted[i] <= remaining; i++) {
path.push(sorted[i]) // choose
backtrack(i, remaining - sorted[i]) // explore (same i: it may be used again)
path.pop() // undo, then try the next candidate
}
}
backtrack(0, target)
return result
}export default function combinationSum(candidates: number[], target: number): number[][] {
// Sorted, so we can stop as soon as a candidate is too big.
const sorted = [...candidates].sort((a, b) => a - b)
const result: number[][] = []
const path: number[] = [] // the combination being built right now
// Only candidates from `start` onward may be added: each combination is built in one order.
function backtrack(start: number, remaining: number): void {
if (remaining === 0) {
result.push([...path]) // found one: save a COPY (path keeps changing)
return
}
// Sorted: once a candidate is bigger than what's left, all later ones are too.
for (let i = start; i < sorted.length && sorted[i] <= remaining; i++) {
path.push(sorted[i]) // choose
backtrack(i, remaining - sorted[i]) // explore (same i: it may be used again)
path.pop() // undo, then try the next candidate
}
}
backtrack(0, target)
return result
}def combination_sum(candidates: list[int], target: int) -> list[list[int]]:
# Sorted, so we can stop as soon as a candidate is too big.
candidates = sorted(candidates)
result = []
path = [] # the combination being built right now
# Only candidates from `start` onward may be added: each combination is built in one order.
def backtrack(start: int, remaining: int) -> None:
if remaining == 0:
result.append(list(path)) # found one: save a COPY (path keeps changing)
return
for i in range(start, len(candidates)):
# Sorted: once a candidate is bigger than what's left, all later ones are too.
if candidates[i] > remaining:
break
path.append(candidates[i]) # choose
backtrack(i, remaining - candidates[i]) # explore (same i: it may be used again)
path.pop() # undo, then try the next candidate
backtrack(0, target)
return result