-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounting-change.js
60 lines (51 loc) · 1.38 KB
/
counting-change.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
51
52
53
54
55
56
57
58
59
60
/**
* Memoized version
*/
export default function countChange(money, coins) {
const map = {};
function countChangeRecur(leftOverMoney, currCoinIndex) {
if (leftOverMoney < 0 || currCoinIndex < 0) {
return 0;
}
if (leftOverMoney === 0) {
return 1;
}
const key = `${leftOverMoney}:${currCoinIndex}`;
if (map[key]) {
return map[key];
}
map[key] =
countChangeRecur(leftOverMoney - coins[currCoinIndex], currCoinIndex) +
countChangeRecur(leftOverMoney, currCoinIndex - 1);
return map[key];
}
return countChangeRecur(money, coins.length - 1);
}
/**
* First attempt
*/
// export default function countChange(money, coins) {
// function countChangeRec(combination, moneyLeft) {
// if (moneyLeft < 0) {
// return;
// }
// if (moneyLeft === 0) {
// combinations.add(combination.sort().join());
// return;
// }
// for (const coin of coins) {
// countChangeRec(combination.concat([coin]), moneyLeft - coin);
// }
// }
// const combinations = new Set();
// countChangeRec([], money);
// return combinations.size;
// }
/**
* Even simpler solution
*/
// export default function countChange(money, coins) {
// if (money < 0 || coins.length === 0) return 0;
// if (money === 0) return 1;
// return countChange(money - coins[0], coins) + countChange(money, coins.slice(1));
// }