mediumBacktrackingBacktracking

Combination Sum

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

Signals to notice

find combinations summing to targetcan reuse elementsunlimited supply

Brute force first

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.

The key insight

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.

What must stay true

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.

Easy way to go wrong

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