-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathleetcode-322-coinChange.js
More file actions
31 lines (26 loc) · 945 Bytes
/
leetcode-322-coinChange.js
File metadata and controls
31 lines (26 loc) · 945 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
25
26
27
28
29
30
31
// p: array, num (int);
// r: num
// e:
// 11
// 1 / 2| 5\
// 10 9 6
// / \ \ / \ \ / \ \
// 9 8 5 5 4 1
// / \ \
// 0 -1 -4
// 0 i i
var coinChange = function (coins, amount) {
const result = count(coins, amount);
return result === Infinity ? -1 : result;
};
const count = (coins, amount, memo = {}) => {
if (amount === 0) return 0;
if (amount < 0) return Infinity;
if (amount in memo) return memo[amount];
let min = Infinity;
for (let coin of coins) {
min = Math.min(min, count(coins, amount - coin, memo));
}
memo[amount] = min + 1;
return min + 1;
};