322. Coin Change -Medium
2017-02-06 20:14
253 查看
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.给你一组不同面额的钱以及资金总额。找到使用硬币组合成该资金总额的最少数量。如果没法组合得到,返回-1
Example
coins = [1, 2, 5], amount = 11return 3 (11 = 5 + 5 + 1)
coins = [2], amount = 3
return -1.
Solution
动态规划解。定义dp[i]:使用硬币组合成资金总额i的最少数量,递推关系式:dp[i] = min(dp[i - coin]) + 1 (coin in coins)。因为dp[i]都需要加上硬币面额中的一个(当然硬币面额一定要小于资金总额),所以我们只要找出到底加上哪个硬币面额使用硬币数量最少即可。对于没法组合得到的资金总额,我们只需初始化的时候设置一个固定较大值,它并不会被更新到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不能被硬币组合得到,那么它对应的d[amount]不会更新 return dp[amount] if dp[amount] != amount + 1 else -1
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- 通过构建一个简单的掷骰子游戏去学习怎么用 Python 编程