zoukankan      html  css  js  c++  java
  • LeetCode 322. Coin Change

    原题

    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]
            
            
    
            
            
            
    

      

  • 相关阅读:
    在 Eclipse 中使用 JUnit4 进行单元测试
    版本控制之道使用Git
    程序员成熟的标志
    Java 编程需要注意的细节
    【netty】netty的websocketframe
    求一个数内含1个次数
    apache bench的使用
    更改centos epel源
    [linux]centos7下解决yum install mysqlserver没有可用包
    cacti的安装与配置
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6694297.html
Copyright © 2011-2022 走看看