题目描述
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.
样例
Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Input: coins = [2], amount = 3
Output: -1
算法1
完全背包问题。
时间复杂度
参考文献
C++ 代码
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> f(amount+1, 0x3f3f3f3f);
int n = coins.size();
f[0] = 0;
for(int i = n-1; i >= 0; i--)
{
for(int j = coins[i]; j <= amount; j++)
f[j] = min(f[j], f[j - coins[i]] + 1);
}
if(f[amount] == 0x3f3f3f3f) return -1;
return f[amount];
}
};