Skip to content
StackDecode
BacktrackingAnimated

Combination Sum

Choose numbers that add up to a target, allowing reuse.

Time

Exponential

Extra space

O(target)

Use it for

Making a total from options.

How it works

  1. Pick numbers (each can be used again and again) that add up to the target.
  2. Try candidates in order, never going back to a smaller one, so each combination appears once.
  3. If the running sum equals the target, record it. If it would go over, prune: this branch and every larger candidate are hopeless.
  4. Otherwise recurse with the new sum, and backtrack afterwards.

Watch it run

Loading animation…