-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCoinChange2.js
41 lines (31 loc) · 857 Bytes
/
CoinChange2.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
/**
* @param {number} amount
* @param {number[]} coins
* @return {number}
*/
var change = function(amount, coins) {
const n = coins.length;
var memo = new Array(n+1);
for (var i = 0; i < memo.length; i++) {
memo[i] = new Array(amount+1);
memo[i].fill(-1);
}
var solve = function(rem, position) {
if(rem == 0) {
return 1;
}
if(position == coins.length) {
return 0;
}
if(memo[position][rem] > -1){
return memo[position][rem]
}
if(rem >= coins[position]) {
memo[position][rem] = solve(rem - coins[position], position) + solve(rem, position + 1)
} else {
memo[position][rem] = solve(rem, position + 1);
}
return memo[position][rem]
};
return solve(amount, 0);
};