Skip to content

Instantly share code, notes, and snippets.

@mbchoa
Last active July 10, 2023 23:33
Show Gist options
  • Save mbchoa/4554125e0502acde65921b5d979257dd to your computer and use it in GitHub Desktop.
Save mbchoa/4554125e0502acde65921b5d979257dd to your computer and use it in GitHub Desktop.
Combination Sum: Finds combination of numbers within a given collection where the sum of the set equals the input target
function findNumberCombinations(numbers, target) {
const result = [];
function backtrack(index, currentCombination, currentSum) {
if (currentSum === target) {
result.push([...currentCombination]);
return;
}
if (currentSum > target || index >= numbers.length) {
return;
}
for (let i = index; i < numbers.length; i++) {
const num = numbers[i];
if (i > index && numbers[i] === numbers[i - 1]) {
continue; // Skip duplicate numbers
}
currentCombination.push(num);
backtrack(i + 1, currentCombination, currentSum + num);
currentCombination.pop();
}
}
numbers.sort((a, b) => a - b); // Sort the input set in ascending order
backtrack(0, [], 0);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment