-
Notifications
You must be signed in to change notification settings - Fork 0
/
countingchange_memoized
56 lines (48 loc) · 1.37 KB
/
countingchange_memoized
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
const mem = [];
function read(n, k) {
return mem[n] === undefined
? undefined
: mem[n][k];
}
function write(n, k, value) {
if (mem[n] === undefined) {
mem[n] = [];
}
mem[n][k] = value;
}
function first_denomination(kinds_of_coins) {
return kinds_of_coins === 1 ? 5 :
kinds_of_coins === 2 ? 10 :
kinds_of_coins === 3 ? 20 :
kinds_of_coins === 4 ? 50 :
kinds_of_coins === 5 ? 100 : 0;
}
// The non-memoized version.
function cc(amount, kinds_of_coins) {
return amount === 0
? 1
: amount < 0 || kinds_of_coins === 0
? 0
: cc(amount, kinds_of_coins - 1)
+
cc(amount - first_denomination(kinds_of_coins),
kinds_of_coins);
}
// The memoized version.
// n is the amount in cents, and k is the number of denominations.
function mcc(n, k) {
if (read(n, k) !== undefined) {
return read(n, k);
} else {
const result = n === 0
? 1
: n < 0 || k === 0
? 0
: n - first_denomination(k) < 0
? mcc(n, k-1)
: mcc(n, k - 1) + mcc(n - first_denomination(k), k);
write(n, k, result);
return result;
}
}
mcc(365, 5); // Expected result: 1730