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.

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  
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • Question You are given coins of different denominations a...
    FlynnLWang阅读 199评论 0 0
  • You are given coins of different denominations and a tota...
    Shiyi001阅读 280评论 0 0
  • 问题描述 You are given coins of different denominations and a...
    codingXue阅读 346评论 0 0
  • 十八岁,对爱情充满期许。 二十岁遇到你,豆蔻年华。 三十岁,家长里短。 四十岁,琐碎不安。 五十岁,平平淡淡。 六...
    幽幽暮色阅读 387评论 0 0