Browse curriculum

FAANGPrep Sprint

Combination Sum

Find every combination that sums to a target, reusing numbers freely, and prune with a sorted break.

Examples

Input:candidates = [2,3,6,7], target = 7
Output:[[2,2,3],[7]]
Explain:

2 + 2 + 3 = 7 uses 2 twice, which is allowed; 7 on its own is the other.

Input:candidates = [2,3,5], target = 8
Output:[[2,2,2,2],[2,3,3],[3,5]]
Explain:

Three combinations; no order within or between them matters.

Input:candidates = [2], target = 1
Output:[]
Explain:

The only candidate is already bigger than the target.

Problem Understanding

Given an array of distinct integers candidates and a target, return a list of all unique combinations where the chosen numbers sum to target.

Key Rule: The same number may be chosen from candidates an unlimited number of times.

Algorithm Strategy

Sort the candidates first. Then backtrack(start, remaining) tries each candidate from start onwards:

  1. Too big? If candidates[i] > remaining, break — the list is sorted, so every candidate after it is too big as well.
  2. Choose it: append it and subtract it from remaining.
  3. Explore with backtrack(i, …) — the same i, because a number may be used again.
  4. Unchoose: pop it before trying the next candidate.

When remaining reaches 0 the path is a combination: record it and return.

Passing i rather than 0 is what keeps each combination unique: a call never goes back to a smaller candidate, so [2, 2, 3] is built once and [3, 2, 2] never is.

Interactive Visualization

ONE NODE PER CALL · THE LABEL IS THE CANDIDATE ADDED, THE NUMBER BELOW IS WHAT IS LEFT · RED = REJECTED BY THE BREAK

SORT THE CANDIDATES

left to make

7

depth

0

Answer

—

path

[] — nothing chosen

candidates (sorted)

2
3
6
7

result

Nothing found yet

 

Sort the candidates — 2, 3, 6, 7 is already in order. Start with an empty path and 7 left to make

Next

Choose 2: the path is [2] and 5 is left

candidates

Target

Every node is one call to backtrack. Its label is the candidate that call added, and the number under it is what is still left to make — a node reading 0 is a combination.

A red node is the one candidate a call looked at and rejected with break: its number goes negative. The candidates after it are never looked at, so they are not drawn at all — that missing part of the tree is the saving. Try Unsorted to see why the sort has to come first.