DSA AnimatorDSA animations
Combination Sum LC #39 Medium Backtracking · Reuse · Pruning
Problem

Given an array of distinct integers candidates and a target integer, return all unique combinations where the chosen numbers sum to target. The same number may be chosen an unlimited number of times.

Example 1
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation: 2+2+3=7 and 7=7.
Example 2
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Explanation: Three ways to reach 8.
Constraints: 1 ≤ candidates.length ≤ 30  |  2 ≤ candidates[i] ≤ 40  |  All distinct  |  1 ≤ target ≤ 40
Try Examples
Custom:
Approach
Backtracking — Recurse with i (Reuse)
Key difference: recurse with i (not i+1) to allow reuse. rem tracks remaining sum. Sort + break when c[i]>rem avoids exceeding target.
Candidates (sorted)
Current Path
curr = [ ] (empty)
Remaining (rem)
—
Results 0 found
Recursion Tree
Step Logic
Press ▶ Play or Next Step to begin.
✅
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Candidates can be reused → recurse with i (not i+1)
2
rem tracks remaining sum; base case rem==0 → found combination
3
Pruning: if c[i]>rem → break (sorted, all further candidates also larger)
4
Sort enables early break pruning
Time
O(n^(t/m))
Space
O(t/m)
Why Backtracking Works

Key difference from Combinations: recurse with i instead of i+1, allowing reuse of the same element. Sorting + break pruning avoids exploring paths that exceed the target. The recursion tree depth is bounded by target/minCandidate.

How to solve Combination Sum

LeetCode 39 · Medium · Backtracking · Pattern: Backtracking + Reuse

Why the obvious approach is slow

Trying every multiset of numbers blindly never ends without a limit. The remaining target gives a natural stopping point.

The key idea

Track the remaining amount, and record the path when it reaches 0. Recurse with the same index i, which allows reusing a number. Sort the candidates, and break as soon as a number is bigger than what remains.

Remember

Pass i, not i plus 1, to allow reuse. Sorting turns "too big" into an early break.

Run the animation above on your own input, or watch the 1:24 video explanation of Combination Sum with a dry run and Java code.

More Backtracking problems