动态规划解决最少硬币凑成m元钱
来源:互联网 发布:国内十大域名注册商 编辑:程序博客网 时间:2024/06/13 17:37
322. Coin Change
- Total Accepted: 30668
- Total Submissions: 120210
- Difficulty: Medium
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
.
public class Solution{ /*长度为m的数组c[1...m]中存放一系列子结果,即c[i]为要凑的钱数为i时所需的最少硬币数,则c[m]为所求 当要找的钱数i(1<i<m)与当前所试探的硬币面值k相等时,结果为1,即c[i]=1 当i大于当前所试探硬币面值k时,若c[i]为0,即还未赋过值,且c[i-k]不为0,即从i元钱中刨去k元后剩下的钱数可以找开, 则c[i]=c[i-k]+1 若c[i]不为0,即已赋过值,则c[i]为c[i-k]+1和c[i]中较小的*/ public int coinChange(int[] coins, int amount) { for(int i=0;i<coins.length;i++) { System.out.println(coins[i]); } int m=amount; int n=coins.length; int[] a=coins; int[] c=new int[m+1];//fu chu zhi 0 if(amount==0) return 0; for(int i=0;i<n;i++) { if(a[i]<=m) { c[a[i]]=1; } } for(int i=1;i<=m;i++) { for(int j=0;j<n;j++) { if(i>a[j]) { if(c[i]==0&&c[i-a[j]]!=0) { c[i]=c[i-a[j]]+1; System.out.println("c"+i+":"+c[i]); } else { if(c[i-a[j]]!=0) { c[i]=c[i-a[j]]+1<c[i]?c[i-a[j]]+1:c[i]; System.out.println("c"+i+":"+c[i]); } } } } } if(c[m]==0) return -1; else return c[m]; }}
另一种更有效的方法
public int coinChange(int[] coins, int amount) { if (amount < 1) return 0; int[] dp = new int[amount + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for (int coin : coins) { for (int i = coin; i <= amount; i++) { if (dp[i - coin] != Integer.MAX_VALUE) { dp[i] = Math.min(dp[i], dp[i - coin] + 1); } } } return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];}
0 0
- 动态规划解决最少硬币凑成m元钱
- 最少硬币问题(动态规划解决)
- 动态规划-最少硬币
- 动态规划:如果我们有面值为1元、3元和5元的硬币若干枚,如何用最少的硬币凑够11元?
- 最少硬币问题 动态规划
- 动态规划之最少硬币
- 最少硬币问题 动态规划
- 动态规划-最少硬币问题
- 动态规划之最少硬币问题
- 最少硬币找零问题-动态规划
- 动态规划(scheme)--求最少硬币数
- 动态规划——最少硬币问题
- 最少硬币找零问题-动态规划
- 动态规划——最少硬币问题
- 动态规划之最少硬币凑钱问题
- 最少硬币(动态规划法,初级)
- 动态规划——最少硬币问题
- 动态规划-最少硬币组合问题
- dvfv
- 淘淘商城---8.7
- 我的一些学习经验:WIFI
- 12、异常
- 20160806,我的第一个博文【关于PHP框架之我见】
- 动态规划解决最少硬币凑成m元钱
- 泛型是什么?为什么要使用泛型?
- 二叉树中两个节点的最近公共祖先节点
- [乐意黎转载]哪些手机或外围设备支持微信运动?
- Android面试整理之SQLite数据库——sql语句和常用函数(一)
- 多线程编程入门(18):线程同步工具之Exchanger
- poj 1236
- 百度语音合成学习
- 关于浮动的练习