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.
// 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.
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.
[2, 2, 2, 2] is valid from candidates = [2, ...]).[2, 2, 3] and [3, 2, 2] are the same multiset — return it once. Your output must contain no duplicate combinations.target = 0 returns [[]]. There is exactly one way to sum to zero: pick nothing. The empty combination is that one way. (target = 0 → [[]], not [].)[]. When no combination reaches a positive target, return an empty list.