Skip to content

Commit d908f88

Browse files
authored
Update 322-coin-change.js
1 parent b142dbe commit d908f88

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

322-coin-change.js

+26
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,29 @@ const coinChange = function(coins, amount) {
1313
}
1414
return dp[amount] === amount + 1 ? -1 : dp[amount]
1515
}
16+
17+
18+
// another
19+
20+
/**
21+
* @param {number[]} coins
22+
* @param {number} amount
23+
* @return {number}
24+
*/
25+
const coinChange = function (coins, amount) {
26+
const n = coins.length
27+
const dp = Array.from({ length: n }, () =>
28+
Array(amount + 1).fill(Infinity)
29+
)
30+
31+
for (let i = 0; i < n; i++) {
32+
dp[i][0] = 0
33+
for (let j = 1; j <= amount; j++) {
34+
if(i > 0) dp[i][j] = dp[i - 1][j]
35+
if (j >= coins[i]) {
36+
dp[i][j] = Math.min(dp[i][j], dp[i][j - coins[i]] + 1)
37+
}
38+
}
39+
}
40+
return dp[n - 1][amount] === Infinity ? -1 : dp[n - 1][amount]
41+
}

0 commit comments

Comments
 (0)