Skip to content

Instantly share code, notes, and snippets.

@iJustErikk
Created December 5, 2020 01:42
Show Gist options
  • Save iJustErikk/60d4f7cdae1ea210e945ddc8dd45a06a to your computer and use it in GitHub Desktop.
Save iJustErikk/60d4f7cdae1ea210e945ddc8dd45a06a to your computer and use it in GitHub Desktop.
// t/f
// use number from numbers as many times as needed to construct targetSum
const canSum = (targetSum, numbers) => {
if (targetSum === 0) return true;
for(let i = 0; i < numbers.length; i += 1) {
const currentNum = numbers[i];
const after = targetSum - currentNum;
if (after < 0) continue;
if(canSum(after, numbers)) return true;
}
return false;
};
console.log(canSum(7, [3, 4, 5, 7]));
console.log(canSum(7, [2, 4]));
// canSum(7, [3, 4, 5, 7]) -> true, as 3 + 4 = 7 or 7 = 7
// canSum(7, [2, 4]) -> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment