zoukankan      html  css  js  c++  java
  • 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.

    Example 1:
    coins = [1, 2, 5], amount = 11
    return 3 (11 = 5 + 5 + 1)

    Example 2:
    coins = [2], amount = 3
    return -1.

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

    这是一道典型的完全DP,首先需要判断是否能凑整,注意初始状态不能全为0,代码如下:

    class Solution(object):
        def coinChange(self, coins, amount):
            """
            :type coins: List[int]
            :type amount: int
            :rtype: int
            """
            if amount == 0:
                return 0
            dp = [amount+1]*(amount+1)
            dp[0] = 0 # fit completely
            for i in xrange(len(coins)):
                for j in xrange(coins[i], amount+1):
                    dp[j] = min(dp[j], dp[j-coins[i]]+1)
                    
            if dp[amount] == amount+1:
                return -1
            else:
                return dp[amount]
  • 相关阅读:
    POJ1704 Georgia and Bob
    BZOJ1299 巧克力棒
    IPSec
    GRE协议
    L2TP协议
    AAA及Radius
    网络安全概论
    路由策略与引入
    BGP协议
    路由协议
  • 原文地址:https://www.cnblogs.com/sherylwang/p/8512060.html
Copyright © 2011-2022 走看看