TRT
Sign in
mediumCoreLeetCode#backtracking#pruning by sum

Combination sum

Find every combination of candidates, each usable any number of times, that adds up to a target, pruning once the sum is too large.

The Runtime Theory Team1 min read
Taught inBacktracking basicsPro — members onlyBacktracking builds a solution one choice at a time, explores each choice recursively and undoes it afterwards. Pruning dead ends early is what makes it practical.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

incandidates = [2, 3, 6, 7], target = 7

out[[2, 2, 3], [7]]

incandidates = [2, 3, 5], target = 8

out[[2, 2, 2, 2], [2, 3, 3], [3, 5]]

incandidates = [2], target = 1

out[]

Given distinct positive candidates and a target, return all unique combinations whose values sum to the target. A candidate may be used any number of times.

Before you code

Reusing a candidate means the recursive call starts at the same index, not the next one. Without a rule like that, the same combination appears in several orders.

Hints

  1. Recurse with (start, remaining). When remaining == 0, record the path.
  2. Loop i from start; choose candidates[i] and recurse with (i, remaining - candidates[i]).
  3. Sort the candidates first. Then, once a candidate exceeds remaining, every later one does too, so break out of the loop.

Production & complexity notes

When solving Combination sum on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Backtracking basics to reinforce the underlying pattern.

What it practices

The choose, explore, unchoose pattern and pruning, from Backtracking basics.

Not started

Sign in to save your learning progress.

Sign in to save