Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit d19835b

Browse files
committed
feat: 找硬币-动态规划版
1 parent 4b6c505 commit d19835b

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const coinChange = (coins, targetAmount) => {
2+
// 初始化备忘录,用Infinity填满备忘录,Infinity说明该值不可以用硬币凑出来
3+
const dp = new Array(targetAmount + 1).fill(Infinity);
4+
5+
// 设置初始条件为0 这一项无法用公式推导出来
6+
dp[0] = 0;
7+
8+
for (let amount = 0; amount <= targetAmount; amount++) {
9+
for (let j = 0; j < coins.length; j++) {
10+
let coin = coins[j];
11+
if (coin <= amount) {
12+
// 根据动态转移方程 求出当前面值需要的硬币数最小值
13+
dp[amount] = Math.min(
14+
dp[amount],
15+
// 比如目标15元 使用5元硬币 拆分为 dp(15 - 5) + 1
16+
dp[amount - coin] + 1
17+
);
18+
}
19+
}
20+
}
21+
22+
// 如果 `dp[amount] === Infinity`说明没有最优解返回-1,否则返回最优解
23+
return dp[targetAmount] === Infinity ? -1 : dp[targetAmount];
24+
};
25+
26+
console.log(coinChange([1, 5, 11], 21))

0 commit comments

Comments
 (0)