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.
典型的动态规划问题,就是背包问题的改版,利用二维数组存储,到当前的硬币为止到达一个数值所用的硬币数,遍历两个维度,寻找到每个硬币为止,能组成一个和值的最小的组成数,利用两个变量存储能达到当前的两种可能,一是不需要当前的硬币就能达到,那么值与之前的值一样,二是加上当前硬币能够达到,那么就是到当前硬币为止的,到达总值剪去当前硬币值的值的数目加上1(当前硬币),然后比较两个值中取小的值,就能够获取较小的值。最后所有硬币达到所求值的结果就被求了出来。
实现代码如下:
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> temp(amount+1,-1);
vector<vector<int> > f(coins.size(),temp );
for(int i=0;i<coins.size();i++)
{
f[i][0]=0;
for(int j=1;j<=amount;j++)
{
int x,y;
if(i>0)
x = f[i-1][j];
else
x=-1;
if(j>=coins[i])
{
y = f[i][j-coins[i]]==-1? -1:f[i][j-coins[i]]+1;
}
else
y=-1;
if(x!=-1&&y!=-1)
f[i][j] = x>y? y:x;
else
if(x==-1&&y==-1)
f[i][j] = -1;
else
f[i][j]=x+y+1;
}
}
return f[coins.size()-1][amount];
}
};