-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbestSum.js
More file actions
24 lines (23 loc) · 888 Bytes
/
Copy pathbestSum.js
File metadata and controls
24 lines (23 loc) · 888 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const bestSum = (targetSum, numbers, cache = { arr: [] }) => {
if (targetSum in cache) return cache[targetSum]
if (targetSum === 0) return []
if (targetSum < 0) return null
let shortestCombination = null;
for (let num of numbers) {
let remainder = targetSum - num;
let remainderResult = bestSum(remainder, numbers, cache)
if (remainderResult != null) {
const combination = [...remainderResult, num];
if(shortestCombination === null || combination.length < shortestCombination.length) {
shortestCombination = combination
}
}
}
cache[targetSum] = shortestCombination
return shortestCombination
}
console.log(bestSum(50, [1, 2, 4]))
console.log(bestSum(7, [5, 3,7, 4]))
console.log(bestSum(8, [2, 5, 3, 7]))
console.log(bestSum(300, [7, 14]))
// console.log(bestSum(40,100))