您的位置:首页 > 其它

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
-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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  动态规划