Coin Change
来源:互联网 发布:js url动态传参数 编辑:程序博客网 时间:2024/05/16 18:31
ou 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.
比较基础的动规题,然而还是提交了三次才改过来。对于这类问题,一般是用一额嵌套的循环。对于这道题,要求的是最小的硬币数,所以amount变量应该放到外层。如果问的是有几种取法,那么需要把coins放在外层(?遇到类似题会更新这篇文章)。
这道题的转移方程是dp[j] = min( dp [j - coins[i]] +1) if j-coins[i] >=0 and dp[j-coins[i]] != MAX_VALUE。
对转移方程的理解是,对于当前的金额,它可以通过一个子规模的最小找零数+1得到,所以最终得到的结果也是最优的。
代码:
public int coinChange(int[] coins, int amount) { if(amount == 0) return 0; if(coins == null || coins.length ==0 || amount <0) return -1; int [] dp = new int [amount+1]; for(int i =1;i<=amount;i++){ dp[i] = Integer.MAX_VALUE; for(int j=0;j<coins.length;j++){ if(i>= coins[j] && dp[i-coins[j]] != Integer.MAX_VALUE){ dp[i] = Math.min(dp[i], dp[i-coins[j]]+1); } } } return dp[amount] == Integer.MAX_VALUE?-1:dp[amount]; }
- Coin Change
- Coin Change
- Coin change
- Coin Change
- Coin change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- coin change
- Coin Change
- 《重构---改善既有代码的设计》总结二之代码的坏味道
- Java设计模式——六大设计原则
- MySQL中INSERT的一般用法
- 给伟伟的java web面试助攻
- 二维码系列(一)生成二维码
- Coin Change
- 二维码系列(二)检测二维码
- Windows 如何在cmd命令行中查看、修改、删除与添加环境变量
- 二维码系列(三)扫描二维码
- 薛(学)问天只是证明了Z=Z就误以为证明了Z=L
- 初识Azure
- 创建第一个Azure Liunx虚拟机
- Linux ssh 登陆
- ubuntu创建新用户并增加管理员权限详解