[LeetCode] 322. Coin Change_Medium tag: backpack

﹏ヽ暗。殇╰゛Y 2021-11-16 07:14 307阅读 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:

  1. Input: coins = [1, 2, 5], amount = 11
  2. Output: 3
  3. Explanation: 11 = 5 + 5 + 1

Example 2:

  1. Input: coins = [2], amount = 3
  2. Output: -1

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

这个题目就是用无限次的01 背包使得target == si’ze of the backpack.

refer: [LeetCode] 系统刷题5_Dynamic Programming

Code:

  1. class Solution:
  2. def coinChange(self, coins, amount):
  3. if not coins or amount < 0: return -1
  4. n = len(coins)
  5. dp = [[float('inf')] * (amount + 1) for _ in range(n + 1)]
  6. for i in range(n + 1):
  7. dp[i][0] = 0
  8. for i in range(1, n + 1):
  9. for j in range(1, amount + 1):
  10. if j >= coins[i - 1]:
  11. dp[i][j] = min(dp[i - 1][j], dp[i][j - coins[i - 1]] + 1)
  12. else:
  13. dp[i][j] = dp[i - 1][j]
  14. return dp[n][amount] if dp[n][amount] < float('inf') else -1

可以用滚动数组将space 优化为O(amount)

转载于:https://www.cnblogs.com/Johnsonxiong/p/11141394.html

发表评论

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

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

相关阅读

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

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