代码改变世界

[LeetCode] 322. Coin Change_Medium tag: backpack

2019-07-06 00:49  Johnson_强生仔仔  阅读(241)  评论(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:

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

Example 2:

Input: coins = [2], amount = 3
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:

class Solution:
    def coinChange(self, coins, amount):
        if not coins or amount < 0: return -1
        n = len(coins)
        dp = [[float('inf')] * (amount + 1) for _ in range(n + 1)]
        for i in range(n + 1):
            dp[i][0] = 0
        for i in range(1, n + 1):
            for j in range(1, amount + 1):
                if j >= coins[i - 1]:
                    dp[i][j] = min(dp[i - 1][j], dp[i][j - coins[i - 1]] + 1)
                else:
                    dp[i][j] = dp[i - 1][j]
        return dp[n][amount] if dp[n][amount] < float('inf') else -1

 

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