function combinationSumK(nums, target) {
const result = [];
function backtrack(start, path, total) {
if (total === target) {
result.push([...path]);
return;
}
if (total > target) return;
for (let i = start; i < nums.length; i++) {
path.push(nums[i]);
backtrack(i + 1, path, total + nums[i]);
path.pop();
}
}
backtrack(0, [], 0);
return result;
}
console.log(combinationSumK([1,2,3], 4));The function finds combinations of unique numbers from the array that sum to 4. Only [1,3] sums to 4. [2,2] is invalid because 2 appears only once in the input. [4] is not in the input. [1,2,3] sums to 6, not 4.
The valid combinations are [1,4] and [2,3]. [1,2,2] is invalid due to repetition. [1,2,3] sums to 6. [5] is not in the array. Thus, there are 2 combinations.
function combinationSum(nums, target) {
const result = [];
function backtrack(start, path, total) {
if (total === target) {
result.push([...path]);
return;
}
if (total > target) return;
for (let i = start; i < nums.length; i++) {
path.push(nums[i]);
backtrack(i, path, total + nums[i]);
path.pop();
}
}
backtrack(0, [], 0);
return result;
}
console.log(combinationSum([2,3,6,7], 7));The combinations are [2,2,3] and [7]. [3,3,3] sums to 9, too big. [2,3,6] sums to 11, too big.
function combinationSum(nums, target) {
const result = [];
function backtrack(start, path, total) {
if (total === target) {
result.push(path);
return;
}
if (total > target) return;
for (let i = start; i < nums.length; i++) {
path.push(nums[i]);
backtrack(i + 1, path, total + nums[i]);
path.pop();
}
}
backtrack(0, [], 0);
return result;
}
console.log(combinationSum([1,2,3], 5));The code pushes the path array directly without copying it. Since path is mutated later, all entries in result point to the same array, causing duplicates.
[3,5] sums to 8 with 2 elements. No single element reaches 8 (max 5). Thus, the minimum is 2.
