算法作业系列14——Coin Change
来源:互联网 发布:看韩国电影的软件 编辑:程序博客网 时间:2024/06/08 16:48
算法作业系列14
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.
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Note:
You may assume that you have an infinite number of each kind of coin.
思路
其实看到第一反应就是,这不是背包问题吗?冥思苦想之下发现自己还是没办法记得背包问题怎么写,因此上维基查了一下,再来动手写这道题。
其实思路很简单,只要想出来状态转移方程怎么写,剩下的就是很短的代码了,那我们就要想,怎么去把这道题转成规模更小的子问题呢?其实很简单,对于每一个数值,只需要减去一个可以交换的硬币面额,再递归求解就可以啦!具体状态转移方程如下:
dp(i) = min{dp(i - p(j))} j=0~n
那当你性质冲冲写完一个递归代码的时候,你会发现,超时了,为什么呢?我们想一下,每次递归都需要计算一下子问题,之前计算的结果没有被很好地保存下来,因此超时也是家常便饭啦。
那怎么解决呢?很简单,空间换时间即可,我们利用for循环,从最小规模算起,利用数组保存当前面额需要的最少组合,如果不能就算成-1,每一次更大规模的问题就以之前的小规模问题求解,这样就可以重复利用之前的结果啦。
参考代码
class Solution {public: int coinChange(vector<int>& coins, int amount) { if (amount == 0) { return 0; } vector<int> dp(amount); for (int i = 1; i <= amount; i++) { dp[i - 1] = -1; for (int j = 0; j < coins.size(); j++) { if (coins[j] <= i && dp[i - coins[j] - 1] != -1 && (dp[i - 1] == -1 || dp[i - coins[j] - 1] < dp[i - 1])) { dp[i - 1] = dp[i - coins[j] - 1] + 1; } } } return dp[amount - 1]; }};
- 算法作业系列14——Coin Change
- DP——Coin Change
- LeetCode—322. Coin Change
- 算法课第14周第1题——322. Coin Change
- hdu(2069)——Coin Change
- 动态规划——322. Coin Change
- HDU 2069 —— Coin Change
- LINTCODE—— Coin Change II
- LeetCode week 14: Coin Change
- leetcode——322——Coin Change
- LeetCode学习篇九——Coin Change
- 一种的多重背包背包——Coin Change
- Coin Change
- Coin Change
- Coin change
- Coin Change
- Coin change
- Coin Change
- VMware Workstation 12.5.7 PRO 安装 CentOS7
- CAN2.0的标准帧和扩展帧格式
- 数据库中空字符串和NULL值两个概念的区别
- ajax的基础知识
- C# Ftp基础操作
- 算法作业系列14——Coin Change
- 19.描述下常用的重构技巧
- LINQ与Lambda表达式的查询语句写法
- 整型
- TimeUnit 使用
- 20.知识面、CDN实现原理
- 运维第一次作业
- Django 应用 -- 发送邮件
- 工具类-汉字转为汉语拼音首字母