codejump
MediumPro challengePythonJavaScriptTypeScript

Backtracking — Combination Sum

AlgorithmsBacktrackingRecursionArrays

candidates holds distinct positive integers. Return every combination of
candidates that adds up to target. The **same candidate may be used any
number of times**; two combinations are the same when they use the same numbers
the same number of times.

Same template as subsets, with two changes: recurse with i (not i + 1) so
a candidate can be picked again, and prune. Once the running sum would pass
target, no larger candidate can help either, so a sorted input lets you stop
the loop early.

Output order (deterministic)

  • Each combination is in ascending order.
  • Combinations are listed in lexicographic order.

Examples

solve([2, 3, 6, 7], 7)  → [[2, 2, 3], [7]]
solve([2, 3, 5], 8)     → [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
solve([2], 1)           → []

Constraints

  • 1 <= candidates.length <= 30, 2 <= candidates[i] <= 40
  • 1 <= target <= 40

Sample tests

Test #1The classic example
Input: [[2,3,6,7],7]
Output: [[2,2,3],[7]]
Test #2Several repeats
Input: [[2,3,5],8]
Output: [[2,2,2,2],[2,3,3],[3,5]]
Test #3Impossible target
Input: [[2],1]
Output: []