{LeetCode} 518. CoinChange2
来源:互联网 发布:linux apm 鸟哥 私房菜 编辑:程序博客网 时间:2024/05/16 12:31
问题:
You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.
Note: You can assume that
- 0 <= amount <= 5000
- 1 <= coin <= 5000
- the number of coins is less than 500
- the answer is guaranteed to fit into signed 32-bit integer
我的代码:
class Solution {public: int change(int amount, vector<int>& coins) { int count = 0; if(amount==0) return 1; else if(coins.empty()) return 0; for(int i=0; i<coins.size();i++) { if(amount==coins.at(i)) { count++; } else if(amount>coins.at(i)) { vector<int> temp(coins); vector<int>::iterator it; for(it=temp.begin();it!=temp.end();) { if(*it>coins.at(i)) { it = temp.erase(it); } else{ it++; } } count+=change(amount-coins.at(i),temp); } } return count; }};
结果:
Submission Result: Time Limit Exceeded
时间复杂度太高了,改用dynamic programming:
class Solution {public: int change(int amount, vector<int>& coins) { vector <vector<int> > dp(coins.size()+1, vector<int>(amount+1)); dp.at(0).at(0)=1; for(int i=1;i<=coins.size();i++) { dp.at(i).at(0)=1; for(int j=1;j<=amount;j++) { dp.at(i).at(j) = dp.at(i-1).at(j) + ((j-coins.at(i-1))>=0? dp.at(i).at(j-coins.at(i-1)):0); } } return dp.at(coins.size()).at(amount); }};
0 0
- {LeetCode} 518. CoinChange2
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- 多栏多列布局
- [leetcode] 529. Minesweeper
- Opengl---gluLookAt函数详解
- 掌握这9段Swift代码,让你教面试官重新做人
- 折中查找(二分查找)
- {LeetCode} 518. CoinChange2
- md5加密
- stuts异常处理实例
- EMS、CEM、OEM、ODM、IDH、IDM之间的联系与区别
- ElasticSearch 5.2.2 安装
- python小练习----秒表
- 根据多选框name来获得选中的值
- 《ACM程序设计》书中题目--problem n
- 数据的接收与发送(练习)