Leetcode 322. Coin Change
来源:互联网 发布:两岸统一知乎 编辑:程序博客网 时间:2024/06/05 03:38
Leetcode 322. Coin Change
source url
题目描述
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.
输入:硬币种类数组、金额
输出:所需要最少的硬币数;无法满足时返回-1
思路
动态规划:用f[i]表示金额为i时,所需要最少硬币数量。此处,考虑类似滑动窗口的情况。对于每个金额,都可根据硬币的种类,并增加一个硬币到达下一个金额。而到达新的金额时,需要判断取已有硬币数量与新硬币数量的较小值。
首先将硬币根据大小进行排序
其次,对f数组进行初始化,对于已有种类,默认置1,即
for(int i =0;i<coins.size()&&coins[i]<=amount;i++){ f[coins[i]] = 1;}
状态转移方程:
那么f[amount]就是答案,复杂度
代码
class Solution {public: int coinChange(vector<int>& coins, int amount) { if(amount==0) return 0; if(coins.size()==0) return -1; sort(coins.begin(),coins.end()); vector<int> f(amount+1,amount+1); for(int i =0;i<coins.size()&&coins[i]<=amount;i++){ f[coins[i]] = 1; } for(int i =coins[0];i<=amount;i++){ for(int j=0;j<coins.size()&&(i+coins[j])<=amount&&(i+coins[j]>0);j++){ f[i+coins[j]] = min(f[i+coins[j]], f[i]+1); } } return f[amount]>=amount+1?-1:f[amount]; }};
0 0
- [leetcode] 322. Coin Change
- leetcode 322. Coin Change
- Leetcode 322. Coin Change
- Leetcode 322. Coin Change
- 322. Coin Change LeetCode
- LeetCode *** 322. Coin Change
- LeetCode 322. Coin Change
- leetcode 322. Coin Change
- LeetCode-322.Coin Change
- Leetcode 322. Coin Change
- [Leetcode]322. Coin Change
- LeetCode 322. Coin Change
- [leetcode] 322. Coin Change
- Leetcode 322. Coin Change
- Leetcode-322.Coin Change
- 【LeetCode】322. Coin Change
- [LeetCode]322. Coin Change
- Leetcode 322. Coin Change
- 利用系统时间计算星期
- java中方法的参数传递机制
- csdn第一篇
- Python
- 生僻字 —— 古文
- Leetcode 322. Coin Change
- Shiro登录验证源码解析
- WebviewJavascriptBridge的使用与介绍
- Android 入门篇检测手机打电话状态
- postgresql 查看数据库,表,索引,表空间以及大小
- JavaScript的异步运行机制
- Picasso源码的简单解析(一)
- Android中关于setLatestEventInfo()过时以及构建Notification的解决方法
- SqlSerVer 列与逗号分隔字符串 互相转换