题目描述
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
我的解题
动态规划
F(S) = F(S-c) + 1;
class Solution {
public:
int coinChangeCore(vector<int>&coins, int amount, vector<int>&count)
{
if(amount<0) return -1;
if(amount==0) return 0;
if(count[amount-1] !=0 ) return count[amount-1];
int min_value = INT_MAX;
for(auto coin: coins)
{
int res = coinChangeCore(coins, amount-coin, count);
if(res>=0 && res<min_value)
{
min_value = res+1;
}
}
count[amount-1] = (min_value ==INT_MAX)? -1:min_value;
return count[amount-1];
}
int coinChange(vector<int>& coins, int amount) {
if(amount==0) return 0;
vector<int>count(amount, 0);
return coinChangeCore(coins, amount, count);
}
};
执行用时 :96 ms, 在所有 C++ 提交中击败了24.66%的用户
内存消耗 :17.9 MB, 在所有 C++ 提交中击败了9.98%的用户