Algorithms · Visualized
Combination Sum
Backtracking
Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.
Finds all unique combinations of numbers from a candidate set that add up to a target, where the same number can be reused multiple times. Time: O(n^(target/min)) average, O(2^target) in the loosest bound, depends heavily on candidate values worst; space: O(target / min candidate) recursion depth.
Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.
Combination Sum
BacktrackingFinds all unique combinations of numbers from a candidate set that add up to a target, where the same number can be reused multiple times. Backtracking tries adding each candidate, recursing with a reduced target, and backtracks when the target goes negative or hits zero.
How Combination Sum Works
- Sort the candidates (helps with early stopping and avoiding duplicate combinations).
- Start the recursion with an empty path and the full target.
- At each step, try each candidate from the current starting index onward (allowing the same index to be reused, since repeats are permitted).
- If adding a candidate makes the remaining target exactly 0, record the current path as a valid combination.
- If the remaining target goes negative, stop that branch (backtrack); otherwise recurse further with the reduced target, then backtrack (remove the candidate) to try the next option.
Combination Sum Worked Example
Input: {candidates: [2, 3, 6, 7], target: 7}
Try 2: remaining=5. Try 2 again: remaining=3. Try 2 again: remaining=1. Try 2 again: remaining=-1, backtrack. Try 3: remaining=0 at path [2,2,3] → record! Backtrack up, try 6 instead of second 2: path[2,6]... continue exploring. Try 7 alone: path[7], remaining=0 → record. Final combinations: [[2,2,3],[7]].
def combination_sum(cand, target):
out = []
def build(i, cur, rem):
if rem == 0:
out.append(cur[:])
return
for j in range(i, len(cand)):
if cand[j] > rem:
break
cur.append(cand[j])
build(j, cur, rem - cand[j]) # reuse same index
cur.pop()
cand.sort()
build(0, [], target)
return outBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Combination Sum Time & Space Complexity
When to Use Combination Sum
- Making change with unlimited coin supply, or any 'reach a target using repeatable building blocks' problem.
- Recipe/formula generation where ingredients can be used multiple times to hit a target quantity.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.