c++100元换零钱换成0.5元、5元和1元,每种货币至少有一个,有多少种组合方法
时间: 2024-06-14 07:03:52 浏览: 20
根据引用[1],我们可以使用递归的方法来解决这个问题。假设我们有一个函数`countChange`,它接受三个参数:剩余金额`amount`、可用货币的面值数组`coins`和当前正在考虑的货币面值的索引`index`。函数的返回值是组合的数量。
首先,我们需要处理一些边界情况。如果剩余金额为0,说明找零成功,返回1。如果剩余金额小于0或者已经考虑完了所有的货币面值,说明找零失败,返回0。
然后,我们可以使用递归的方式来计算组合的数量。对于当前考虑的货币面值,我们有两种选择:要么使用这个面值的货币,要么不使用。如果选择使用这个面值的货币,我们需要将剩余金额减去这个面值,并且继续考虑当前面值的货币。如果选择不使用这个面值的货币,我们直接考虑下一个面值的货币。最后,我们将两种选择的结果相加,即可得到总的组合数量。
下面是一个使用C++实现的例子:
```cpp
#include <iostream>
#include <vector>
int countChange(int amount, std::vector<int>& coins, int index) {
// 边界情况
if (amount == 0) {
return 1;
}
if (amount < 0 || index >= coins.size()) {
return 0;
}
// 递归计算组合数量
int count = 0;
// 使用当前面值的货币
count += countChange(amount - coins[index], coins, index);
// 不使用当前面值的货币
count += countChange(amount, coins, index + 1);
return count;
}
int main() {
int amount = 100;
std::vector<int> coins = {0.5, 5, 1};
int combinations = countChange(amount, coins, 0);
std::cout << "There are " << combinations << " combinations." << std::endl;
return 0;
}
```
运行上述代码,将输出组合的数量。