Combination Sum

35 min · combinationSum()

A café has a short menu of voucher values, and you may use any voucher as many times as you like. The interesting part isn't finding one way to pay — it's finding every way.

Treat the distinct positive integers in candidates as the voucher values you can use. Build every unique combination — a selection where order doesn't create a new answer — whose values add up to target.

The output follows these rules:

  • You may reuse any candidate an unlimited number of times.
  • Write each combination in non-decreasing order, so every next value is at least the previous one.
  • Return no duplicate combinations. The outer list may be in any order.
  • Return [] when no combination reaches the target.

Constraints

  • 1 <= candidates.length <= 8
  • 2 <= candidates[i] <= 40
  • All values in candidates are distinct.
  • 1 <= target <= 40

Hints

Count copies directly

For a candidate value v, only 0 through target // v copies can fit. Trying every count for each candidate gives you a correct baseline.

Sort, then stop early

Sort a copy of candidates. During the search, once a candidate is larger than the remaining sum, every later candidate is too large as well.

Reuse without reordering

After choosing candidates[i], recurse from index i, not i + 1, so that value may be chosen again. Never move backward; that keeps combinations non-decreasing and prevents reordered duplicates.

Follow-up

What changes if each candidate may be used only once and the input itself can contain duplicate values?

Visible cases

Examples

Example 1

ready
Input
candidates = [
  2,
  3,
  6,
  7
]
target = 7
Expected
[
  [
    2,
    2,
    3
  ],
  [
    7
  ]
]
Why
2 + 2 + 3 and the single 7 are the two unique combinations

Example 2

ready
Input
candidates = [
  2,
  3,
  5
]
target = 8
Expected
[
  [
    2,
    2,
    2,
    2
  ],
  [
    2,
    3,
    3
  ],
  [
    3,
    5
  ]
]
Why
reusing values finds three non-decreasing ways to total 8

Example 3

ready
Input
candidates = [
  2
]
target = 1
Expected
[]
Why
the only candidate already exceeds the target

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite