leetcode@ [322] Coin Change (Dynamic Programming)
2016-01-04 16:49
190 查看
https://leetcode.com/problems/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
Example 1:
coins =
return
Example 2:
coins =
return
Note:
You may assume that you have an infinite number of each kind of coin.
View Code
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.
class Solution { public: int dfs(int amount, vector<int>& coins, vector<int>& dp) { if(amount == 0) return 0; if(amount < 0) return INT_MAX; if(dp[amount]) return dp[amount]; int minChange = INT_MAX; for(int i=0;i<coins.size();++i) { int eachChange = dfs(amount-coins[i], coins, dp); if(eachChange == INT_MAX) minChange = min(minChange, INT_MAX); else minChange = min(minChange, eachChange + 1); } dp[amount] = minChange; return dp[amount]; } int coinChange(vector<int>& coins, int amount) { int n = coins.size(); if(n == 0 && amount > 0) return -1; if(n == 0 && amount == 0) return 0; vector<int> dp(amount+1, 0); dp[amount] = dfs(amount, coins, dp); if(dp[amount] == INT_MAX) return -1; else return dp[amount]; } };
View Code
相关文章推荐
- 汇编指令(转载)
- [java] jstack 查看死锁问题
- iPad Air/Air2/iPhone6 Plus跑分对比
- 老李推荐:第6章2节《MonkeyRunner源码剖析》Monkey原理分析-事件源-事件源概览-获取命令字串
- 自动变色自定义View和自定义关键字变色TextView
- ios基础之调试篇
- struts拦截器
- 深入浅出 消息队列 ActiveMQ
- 金融类app各种数值的精确计算问题
- 装饰模式
- 如何查看DBF文件
- app移动端与后台交互和效率提升
- 什么是FastCGI?
- 老李推荐:第6章1节《MonkeyRunner源码剖析》Monkey原理分析-事件源-事件源概览 2
- 如何使用wifi定位技术预防老人痴呆症走丢
- AngularJS Bootstrap
- Java-synchronized的用法
- 自定义ContentProvider的一些细节探究
- Java使用MyEclipse构建webService简单案例
- c++中*与&的区别