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]
            
            
    
            
            
            
    

      

  • 相关阅读:
    content type
    存储过程查询并插入到临时表
    jdk 生成证书
    sql 表值函数-将一个传入的字符串用2中分隔符拆分成临时表
    sql 把一个用逗号分隔的多个数据字符串变成一个表的一列
    sql 分隔字符串函数
    md5 加密
    SQL语句的使用
    WINDOW的cmd的命令【转载】
    zookeeper安装
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6694297.html
Copyright © 2011-2022 走看看