mediumBacktrackingBacktracking

Combination Sum

mediumTime: O(n^(t/m))Space: O(t/m)

Recognize the pattern

find combinations summing to targetcan reuse elementsunlimited supply

Brute force idea

The naive version of Combination Sum sounds like this: Not applicable — enumeration IS the problem. But naive recursion without pruning explores dead branches. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

Better approach

The deeper shift in Combination Sum is this: Backtracking with pruning: sort candidates, start from current index (allowing reuse), subtract from remaining target. Stop when target < 0 or target = 0 (found a valid combination). The sort enables early termination. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Combination Sum is one steady idea: By always choosing from index i or later (not earlier), you avoid generating the same combination in different orders. Sorting lets you prune: if candidates[j] > remaining, skip j and everything after. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

The trap in Combination Sum usually looks like this: Generating duplicates like [2,3,2] and [2,2,3] — always choose from the current index onward. Also, not sorting means you can't prune branches early. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Backtracking Pattern