322. Coin Change

2018-07-16  本文已影响0人  JERORO_

问题描述

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 (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.

思路

  1. 运用动态规划,用一个list记录0至amount之间,凑到各个价格所需要的coin数量,初始除了价格为0时需要0个coin,其余价格需要inf个
  2. 从小到大循环一遍,对于每个coin:
    凑到某个价格X所需要的coin数量 = 当前所需数量凑到(X-coin)的价格所需要的coin数量+1间的最小值
    def coinChange(self, coins, amount):
        """
        :type coins: List[int]
        :type amount: int
        :rtype: int
        """
        dp = [0] + [float('inf')] * amount
        coins.sort()
        for c in coins:
            for i in range(c, amount+1):
                dp[i] = min(dp[i], dp[i-c]+1)
        return dp[-1] if dp[-1] != float('inf') else -1  
上一篇下一篇

猜你喜欢

热点阅读