题目:给定不同面额的硬币coins和每种硬币的数量counts,以及一个总金额amount
编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回-1.
示例输入
1 2 5// 硬币面额coins
3 2 1// 每种面额对应的数量counts
11// 总金额amount
示例输出
5
#include <vector>
#include <iostream>
using namespace std;
// count为硬币个数
// sum为当前和
int backtracking(int &count, vector<int> coins, int startindex, int sum, int amount) {
if (startindex == coins.size()) {
return -1;
}
if (sum == amount) {// 当前和满足amount,立即返回
return sum;
}
for (int i = startindex; i < coins.size(); ++i) {
if (sum + coins[i] > amount)
continue;
count++;
sum += coins[i];
if (backtracking(count, coins, i + 1, sum, amount) == amount)
return amount;
sum -= coins[i];
count--;
}
}