LeetCode 322. Coin Change

时间:2021-10-25 14:49:10

原题

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

Note:
You may assume that you have an infinite number of each kind of coin.

示例

Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)

Example 2:
coins = [2], amount = 3
return -1.

思路

比较典型的动态规划题目。要确定每个amount最少需要多少硬币,可以用amount依次减去每个硬币的面值,查看剩下总额最少需要多少硬币,取其中最小的加一即是当前amount需要的最少硬币数,这样就得到了递推公式,题目就迎刃而解了。

代码实现

# 动态规划
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
# 边界条件
if amount == 0:
return 0
# 存储之前计算过的结果
dp = [sys.maxint] * (amount + 1)
dp[0] = 0
# 自底向下编写递推式
for i in xrange(1,amount+1):
for j in xrange(len(coins)):
if (i >= coins[j] and dp[i - coins[j]] != sys.maxint):
# 当前数额的最小步数
dp[i] = min(dp[i], dp[i - coins[j]] + 1) # 如果最小步数等于最大值,则代表无解
return -1 if dp[amount] == sys.maxint else dp[amount]