Last active
July 10, 2023 23:33
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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