Skip to content

Instantly share code, notes, and snippets.

@iJustErikk
Created December 5, 2020 02:38
Show Gist options
  • Save iJustErikk/dc832a110e8a55c2c3f79f2dca3b379c to your computer and use it in GitHub Desktop.
Save iJustErikk/dc832a110e8a55c2c3f79f2dca3b379c to your computer and use it in GitHub Desktop.
// finds what combination of nums in numbers generates targetsum
const howSum = (targetSum, numbers) => {
if (targetSum === 0) return [];
if (targetSum <= 0) return null;
for (let num of numbers) {
const remainder = targetSum - num;
const res = howSum(remainder, numbers);
if (res === null) continue;
res.push(num);
return res;
}
return null;
};
console.log(howSum(7, [3,4]));
console.log(howSum(7, [3, 4, 5, 7])); //returns 3,4 or 7
console.log(howSum(7, [2, 4]));// returns null
console.log(howSum(300, [7, 14]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment