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

  • 相关阅读:
    Linux安装步骤
    Python邮件发送
    拉链表
    Hive
    Shell笔记
    Hadoop入门
    Thinkphp手把手练习
    Shell学习日记
    Linux安装mysql数据库
    Oracle集合操作
  • 原文地址:https://www.cnblogs.com/xxswkl/p/12327962.html
Copyright © 2011-2022 走看看