DP问题:leetcode(322) Coin Change
2018-01-29 09:42
459 查看
问题描述:
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.
诶,弄了好久才AC,数组下标弄混了。。。另外该题的测试用例应该是硬币种类远小于要组成的amount的大小的。
主要思路:采用时间复杂度为O(n*coinlen)的动态规划算法,coinlen表示金币的种类。a[i]表示组成i个单位的钱所需要的最少的硬币数量。外循环中i从1遍历到amount,内循环中j从0遍历到coinlen-1,j表示硬币种类的下标,则a[i]=min{1+a[i-coin(j)]}。这道题开始C++代码用vector<int>a(amount+1,-1)来初始化数组,而不再用静态大小的数组。
代码:
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.
诶,弄了好久才AC,数组下标弄混了。。。另外该题的测试用例应该是硬币种类远小于要组成的amount的大小的。
主要思路:采用时间复杂度为O(n*coinlen)的动态规划算法,coinlen表示金币的种类。a[i]表示组成i个单位的钱所需要的最少的硬币数量。外循环中i从1遍历到amount,内循环中j从0遍历到coinlen-1,j表示硬币种类的下标,则a[i]=min{1+a[i-coin(j)]}。这道题开始C++代码用vector<int>a(amount+1,-1)来初始化数组,而不再用静态大小的数组。
代码:
#include<iostream> #include<vector> #include<cstring> #include<cmath> using namespace std; class Solution { public: int coinChange(vector<int>& coins, int amount) { int len=coins.size(); vector<int>a(amount+1,-1); a[0]=0; if(amount==0) return 0; for(int i=0;i<len;i++){ if(coins[i]<=amount) a[coins[i]]=1; } int min,flag; for(int i=1;i<=amount;i++){ if(a[i]==-1){ min=100000,flag=0; for(int j=0;j<len;j++){ if(i-coins[j]>=0&&a[i-coins[j]]!=-1&&a[coins[j]]!=-1){ min=(min<1+a[i-coins[j]]?min:1+a[i-coins[j]]); flag=1; } } if(flag==1) a[i]=min; } } return a[amount]; } }; int main() { int arr[]={1,2147483647}; vector<int>coins(arr,arr+sizeof(arr)/sizeof(int)); int amount=2; cout<<(new Solution())->coinChange(coins,amount); }
相关文章推荐
- LeetCode 322 Coin Change (完全背包)
- LeetCode.322(518) Coin Change && Coin Change2
- 322 LeetCode Coin Change
- leetcode322 coin change & leetcode343 integer break
- DP7 两道换硬币的问题 Coin Change @geeksforgeeks
- Leetcode (322) Coin Change
- 利用动态规划(DP)解决 Coin Change 问题
- 322. Coin Change
- lightoj1231--Coin Change (I)(简单dp,背包计数)
- 322. Coin Change
- leetcode 740. Delete and Earn 抢劫问题的改版 + 动态规划DP
- DP问题—Leetcode 64. Minimum Path Sum
- 322. Coin Change
- 322. Coin Change
- hdu2069 Coin Change ——DP
- LeetCode Coin Change
- 322. Coin Change
- DP问题:leetcode(91) Decode Ways
- leetcode 53. Maximum Subarray(DP动态规划问题)
- LeetCode | 746. Min Cost Climbing Stairs | 简单DP上楼梯问题