-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbestsum.js
50 lines (34 loc) Β· 1.05 KB
/
bestsum.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
'use strict';
function bestSum(targetSum, numbers, memo = {}) {
if (targetSum in memo) {
return memo[targetSum];
}
if (targetSum === 0) {
return [];
}
if (targetSum < 0) {
return null;
}
let shortestCombination = null;
for (let i = 0; i < numbers.length; i++) {
shortestCombination = bestSum(targetSum - numbers[i], numbers, memo);
if (shortestCombination !== null) {
if (targetSum in memo) {
if (memo[targetSum].length > shortestCombination.length) {
memo[targetSum] = shortestCombination;
}
} else {
memo[targetSum] = shortestCombination;
}
memo[targetSum].push(numbers[i]);
}
}
memo[targetSum] = shortestCombination;
return memo[targetSum];
}
console.log(bestSum(7, [5, 3, 4, 7]));
console.log(bestSum(7, [2, 3, 8]));
console.log(bestSum(7, [2, 4]));
console.log(bestSum(2, [2, 0]));
console.log(bestSum(300, [7, 14]));
console.log(bestSum(500, [2]));