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:

Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

题目大意:

使用几种硬币找零钱,每种硬币可多次使用,求所需硬币最少数目。若硬币之和不能等于零钱总数,输出-1.

解题思路:

用递归的动态规划解决

 class Solution {
public: const int inf = ;
vector<vector<int>> v;
int search(vector<int>& coins, int amount, int idx) {
if (amount == )
return ;
if (idx >= coins.size() || amount < )
return inf;
if (v[idx][amount] >= )
return v[idx][amount];
int a = search(coins, amount - coins[idx], idx);
int b = search(coins, amount, idx + );
v[idx][amount] = min(a + , b);
return v[idx][amount];
} int coinChange(vector<int>& coins, int amount) {
v.resize(coins.size(), vector<int>(amount + , -));
int ans = search(coins, amount, );
if (ans < inf)
return ans;
return -;
}
};

方法二:迭代

定义一个大小为amount + 1的数组dp,dp[i]代表当总钱币数为i时可兑换的最少的钱币个数,

当i为0时只需要0个钱币,因此dp[0]等于0。

当求dp[k]时,先令dp[k]等于正无穷,然后遍历所有钱币,若钱币j币值coins[j]小于k,令dp[k] = min(dp[k - coins[j] ] + 1, dp[k])。

 class Solution {
public:
const int inf = ;
vector<int> dp;
int coinChange(vector<int>& coins, int amount) {
int N = coins.size();
dp.resize(amount + );
dp[] = ;
for (int i = ; i <= amount; i++) {
dp[i] = inf;
for (int j = ; j < N; j++) {
if (coins[j] <= i)
dp[i] = min(dp[i], dp[i - coins[j]] + );
}
}
if (dp[amount] == inf)
return -;
return dp[amount];
}
};

最新文章

  1. mysql的缓冲查询和非缓冲查询
  2. 图像处理中任意核卷积(matlab中conv2函数)的快速实现。
  3. Android 框架学习之 第一天 okhttp &amp; Retrofit
  4. 介绍对称加密的另一个算法——PBE
  5. 在 Github 上找「好东西」的方法
  6. 64位CentOS源码编译方式安装wine
  7. [转]mysql分布式方案-分库拆表
  8. 简单谈谈Resource,Drawable和Bitmap之间的转换
  9. Android 学习笔记之Volley开源框架解析(三)
  10. Win10 10586 更新
  11. [SAM4N学习笔记]按键程序(查询方式)
  12. MySQL外键约束On Delete、On Update各取值的含义
  13. 淘宝开源任务调度框架tbschedule
  14. cPanel下载及安装信息 /usr/local/cpanel/bin/adduser--&gt;realadduser
  15. python 数据类型 -- set
  16. [Bootstrap 源码]——bootstrap源码之初始化
  17. for in,Object.keys()与for of的区别
  18. 19.3.20 cmd操作:1.dir查看当前文件夹内的文件;2.alt+space+c关闭cmd窗口
  19. ES 6 系列 - 赋值的新方式:解构赋值
  20. 解决JFinal多文件上传时只获取到第一个文件名

热门文章

  1. iptables 命令记录
  2. PIE SDK点元素的绘制
  3. yum lnmp全家桶
  4. pip install xxx -i https://pypi.tuna.tsinghua.edu.cn/simple
  5. Oracle 基础系列之1.1 oracle的安装
  6. BNU27935——我爱背单词——————【数组模拟】
  7. bzoj 5084: hashit
  8. java开发中的设计模式
  9. C#基础(第一天)
  10. 5、Angular2 Injectable 服务