-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path322-coin-change.js
More file actions
74 lines (60 loc) · 1.95 KB
/
Copy path322-coin-change.js
File metadata and controls
74 lines (60 loc) · 1.95 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// https://leetcode.com/problems/coin-change/description/
var coinChange = function (coins, amount) {
// const result = coinChangeTopBottom(coins, amount);
const result = coinChangeBottomTop(coins, amount);
return result;
};
var coinChangeBottomTop = function (coins, amount) {
const dp = [0];
for(let i = 1; i <= amount; i++) {
let minCoins = Number.MAX_SAFE_INTEGER;
for (const coin of coins) {
const coinsUsed = (dp[i - coin] ?? Number.MAX_SAFE_INTEGER) + 1;
minCoins = Math.min(minCoins, coinsUsed);
}
dp[i] = minCoins;
}
const result = dp[amount];
return result === Number.MAX_SAFE_INTEGER ? -1 : result;
}
var coinChangeTopBottom = function (coins, amount) {
const memo = {};
const dfs = (amountLeft) => {
if (memo[amountLeft]) {
return memo[amountLeft];
}
if (amountLeft === 0) {
return 0;
}
let minCoins = Number.MAX_SAFE_INTEGER;
for(let i = 0; i < coins.length; i++) {
const newAmount = amountLeft - coins[i];
if (newAmount < 0) {
continue;
}
const answer = dfs(newAmount) + 1;
minCoins = Math.min(minCoins, answer);
}
memo[amountLeft] = Math.min(memo[amountLeft] ?? Number.MAX_SAFE_INTEGER, minCoins);
return minCoins;
}
const result = dfs(amount);
return result === Number.MAX_SAFE_INTEGER ? -1 : result;
}
const data = [
{coins: [2], amount: 1, output: -1},
{ coins: [1, 4, 5], amount: 13, output: 3 },
{ coins: [1,2,3,4,5], amount: 7, output: 2 },
{ coins: [186, 419, 83, 408], amount: 6249, output: 20 },
{ coins: [1, 2, 5], amount: 11, output: 3 },
{ coins: [5, 2, 1], amount: 11, output: 3 },
{ coins: [2], amount: 3, output: -1 },
{ coins: [1], amount: 0, output: 0 },
];
for (let d of data) {
console.log(JSON.stringify(d));
const result = coinChange(d.coins, d.amount);
console.log('result = ', result);
(result === d.output) ? console.log('ok') : console.error('nok');
console.log('----------');
}