给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1
。
示例 1:
输入: coins = [1, 2, 5], amount = 11输出: 3
解释: 11 = 5 + 5 + 1
示例 2:
输入: coins = [2], amount = 3
输出: -1
说明:
你可以认为每种硬币的数量是无限的。
1.自顶向下+备忘录:
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if(amount < 1) return 0;
vector<int> res(amount+1,0);
return dp(coins,amount,res);
}
int dp(vector<int>& coins, int amount,vector<int>& res){
int q=INT_MAX;
if(amount == 0) return 0;
if(res[amount] != 0)
return res[amount];
if(amount < 0)
return -1;
else{
for(int i=0;i<coins.size();i++){
int tmp=dp(coins,amount-coins[i],res);
if(tmp>=0 && tmp<q)
q=tmp+1;
}
}
res[amount] = q==INT_MAX ? -1 : q;
return res[amount];
}
};
2.自底向上的方法:
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int Max = amount +1;
vector<int> dp(amount + 1, Max);
dp[0]=0;
for(int i=1;i<=amount;i++) //从下到上,即从1元找零开始,推到题目给的amount
for(int j=0;j<coins.size();j++) //对每个钱数找零情况,都从最小的零钱开始找,逐步更新零钱面额增大的最小找钱情况
if(coins[j]<=i)
dp[i]=min(dp[i],dp[i-coins[j]]+1); //min中dp[i]的更新条件是用了1个此面额找完钱后,剩下的amount需要零钱个数+1会小于不用此面额找钱的个数(不用此面额找钱的个数初始设为最大)
return dp[amount] > amount ? -1 : dp[amount]; //dp[amount] > amount 是初始为真的
}
}
3.各面额零钱个数有限的情况
作者:2017gdgzoi999
原文:https://blog.csdn.net/drtlstf/article/details/80258580
用dfs
Description
有1元、5元、10元、50元、100元、500元的硬币各c1、c5、c10、c50、c100、c500枚。现在要用这些硬币来支付A元,最少需要多少枚硬币?假定本题至少存在一种支付方案。
Input
一行c1、c5、c10、c50、c100、c500、A,中间用空格隔开。
Output
最少的硬币数量。
Sample Input
3 2 1 3 0 2 620
Sample Output
6
HINT
【注释】
500元硬币1枚,50元硬币2枚,10元硬币1枚,5元硬币2枚,合计6枚。
【限制条件】
0<= c1、c5、c10、c50、c100、c500<=10^9
0<=A<=10^9
---------------------
#include <iostream>
#define SIZE 501
using namespace std;
int a[SIZE], c[6] = {500, 100, 50, 10, 5, 1};
int dfs(int l, int k) // 深度优先搜索
{
int i;
if (!l)
{
return k;
}
for (i = 0; i < 6; i++)
{
if ((l >= c[i]) && (a[c[i]]))
{
a[c[i]]--; // 数量-1
return dfs(l - c[i], k + 1); // 继续搜索
}
}
}
int main(int argc, char** argv)
{
int l;
cin >> a[1] >> a[5] >> a[10] >> a[50] >> a[100] >> a[500] >> l; // 读入数据
cout << dfs(l, 0) << endl;
return 0;
}