coin change

爱被打了一巴掌 2021-12-17 10:47 340阅读 0赞

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.

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

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

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

这是一道典型的完全DP,首先需要判断是否能凑整,注意初始状态不能全为0,代码如下:

  1. class Solution(object):
  2. def coinChange(self, coins, amount):
  3. """
  4. :type coins: List[int]
  5. :type amount: int
  6. :rtype: int
  7. """
  8. if amount == 0:
  9. return 0
  10. dp = [amount+1]*(amount+1)
  11. dp[0] = 0 # fit completely
  12. for i in xrange(len(coins)):
  13. for j in xrange(coins[i], amount+1):
  14. dp[j] = min(dp[j], dp[j-coins[i]]+1)
  15. if dp[amount] == amount+1:
  16. return -1
  17. else:
  18. return dp[amount]

转载于:https://www.cnblogs.com/sherylwang/p/8512060.html

发表评论

表情:
评论列表 (有 0 条评论,340人围观)

还没有评论,来说两句吧...

相关阅读

    相关 322. Coin Change(硬币兑换dp)

    您会得到不同面额的硬币和总金额。编写一个函数来计算组成该数量所需的最少数量的硬币。如果这笔钱不能用硬币的任何组合来弥补,请返回-1。 范例1: 输入:硬币= \[1, 2,