Combinations for Target SumLoading saved progress…

Combinations for Target Sum

You have a set of coin denominations and an amount to make. You want every distinct way to make that amount, where each denomination can be used as many times as you like. Implement combinationsTargetSum(candidates, target) — given an array of distinct positive integers and a target sum, return all the unique combinations of candidates that add up exactly to target. Each candidate may be reused an unlimited number of times, and the same multiset of numbers must not appear twice in the output. This is the classic Combination Sum problem.

Signature

// candidates: number[]  — distinct positive integers, e.g. [2, 3, 6, 7]
// target:     number    — a non-negative integer to sum to
// returns:    number[][] — every unique combination summing to target.
//   Each inner combination is sorted non-decreasing.
//   The outer list is sorted (lexicographically by the numbers it contains).
function combinationsTargetSum(candidates, target): number[][];

A combination is a multiset: [2, 2, 3] and [3, 2, 2] are the same combination, so only one of them appears. Order within a combination does not carry meaning — we pick the non-decreasing form as the canonical one.

Examples

combinationsTargetSum([2, 3, 6, 7], 7);
// → [[2, 2, 3], [7]]
// 2+2+3 = 7 (reusing 2 twice) and 7 alone. 6 leads nowhere: 6+anything overshoots.
combinationsTargetSum([2, 3, 5], 8);
// → [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
// Three ways: four 2s; one 2 and two 3s; one 3 and one 5.
combinationsTargetSum([2], 1);
// → []
// 2 already exceeds the target of 1, so there is no way to reach it.
combinationsTargetSum([5], 10);
// → [[5, 5]]
// A single candidate that divides the target: use it twice.

Notes

  • Unlimited reuse. Each candidate can appear any number of times in a combination ([2, 2, 2, 2] is valid from candidates = [2, ...]).
  • Unique combinations only. [2, 2, 3] and [3, 2, 2] are the same multiset — return it once. Your output must contain no duplicate combinations.
  • Candidates are distinct positive integers. No zeros, no negatives, no repeats in the input. You don't need to guard against those.
  • Output ordering is fixed. Each inner combination is sorted non-decreasing, and the outer array is sorted (compare element-by-element). The tests assert this exact shape, so a correct set of combinations in the wrong order will still fail.
  • target = 0 returns [[]]. There is exactly one way to sum to zero: pick nothing. The empty combination is that one way. (target = 0[[]], not [].)
  • No solution returns []. When no combination reaches a positive target, return an empty list.
Loading editor…