322零钱兑换

题目:给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
链接:https://leetcode-cn.com/problems/coin-change

法一:自己的代码

思路:动态规划,dp[i]表示兑换i的最少硬币个数,则dp[i]=min(dp[i-j] for j in coins),

from typing import List
class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp = [0] + [float('inf')] * amount
        m = min(coins)
        # 从最小的位置开始遍历
        for i in range(m,amount+1):
            k = float('inf')
            for j in coins:
                p = i - j
                if p >= 0:
                    k = min(k, dp[p] + 1)
            dp[i] = k
        return dp[-1] if dp[-1] != float('inf') else -1
if __name__ == '__main__':
    duixiang = Solution()
    # a = duixiang.coinChange(coins = [281,20,251,251], amount = 7323)
    # a = duixiang.coinChange(coins = [1, 2, 5], amount = 11)
    a = duixiang.coinChange(coins = [2], amount = 3)
    # a = duixiang.coinChange(coins = [2,3], amount = 2.5)
    print(a)
View Code

ttt

法二:

https://leetcode-cn.com/problems/coin-change/solution/dong-tai-gui-hua-tao-lu-xiang-jie-by-wei-lai-bu-ke/

posted on 2020-02-18 20:58  吃我一枪  阅读(162)  评论(0编辑  收藏  举报

导航