国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

322. Coin Change -Medium

2019-11-11 04:23:18
字體:
供稿:網(wǎng)友

Question

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.

給你一組不同面額的錢以及資金總額。找到使用硬幣組合成該資金總額的最少數(shù)量。如果沒法組合得到,返回-1

Example

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


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

Solution

動態(tài)規(guī)劃解。定義dp[i]:使用硬幣組合成資金總額i的最少數(shù)量,遞推關(guān)系式:dp[i] = min(dp[i - coin]) + 1 (coin in coins)。因為dp[i]都需要加上硬幣面額中的一個(當然硬幣面額一定要小于資金總額),所以我們只要找出到底加上哪個硬幣面額使用硬幣數(shù)量最少即可。對于沒法組合得到的資金總額,我們只需初始化的時候設(shè)置一個固定較大值,它并不會被更新到

class Solution(object): def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ dp = [0] + [amount + 1] * amount for a in range(1, amount + 1): for c in coins: # 只對小于amount的硬幣進行判斷 if a >= c: dp[a] = min(dp[a], dp[a - c] + 1) # 如果amount不能被硬幣組合得到,那么它對應(yīng)的d[amount]不會更新 return dp[amount] if dp[amount] != amount + 1 else -1
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 东兰县| 陇川县| 浦江县| 正安县| 冕宁县| 高安市| 阿鲁科尔沁旗| 扶风县| 鹿泉市| 开封市| 称多县| 额尔古纳市| 茌平县| 桑日县| 南皮县| 尚义县| 绥中县| 大连市| 曲阳县| 武山县| 洪雅县| 桂东县| 黔南| 谷城县| 徐水县| 太仓市| 宜良县| 民县| 西充县| 西畴县| 镇康县| 新田县| 平江县| 六枝特区| 阿拉尔市| 汉川市| 汉寿县| 镇雄县| 县级市| 晋中市| 潞城市|