日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 322. Coin Change

發布時間:2023/12/9 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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]

  

轉載于:https://www.cnblogs.com/LiCheng-/p/6694297.html

總結

以上是生活随笔為你收集整理的LeetCode 322. Coin Change的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。