Skip to content

Commit e07a863

Browse files
committed
feat: coin change by dp
1 parent f32702a commit e07a863

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

greedy.coin-change.py

+17
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,23 @@ class Solution:
1010
你可以认为每种硬币的数量是无限的。
1111
"""
1212
def coinChange(self, coins: List[int], amount: int) -> int:
13+
dp = [amount + 1] * (amount + 1)
14+
dp[0] = 0
15+
16+
# 从 1 遍历到 amount
17+
for i in range(1, amount + 1):
18+
for coin in coins:
19+
# 如果当前面额大于当前的硬币,并且扣除了当前硬币后,仍有值
20+
if i - coin >= 0 and dp[i - coin] != amount + 1:
21+
# 定义状态方程
22+
dp[i] = min(dp[i], 1 + dp[i - coin])
23+
24+
if dp[amount] == amount + 1:
25+
dp[amount] = -1
26+
27+
return dp[amount]
28+
29+
def coinChangeByGreedy(self, coins: List[int], amount: int) -> int:
1330
if amount == 0:
1431
return 0
1532

0 commit comments

Comments
 (0)