问题描述:项目欧拉#31
在英格兰的货币是由英镑,£和便士,p和 有八个硬币一般循环:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
有可能以下列方式使£2:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
多少种方式可以£2使用任意数量的硬币进行?
我试图想出我自己的算法,并失败了。所以,我来到this one(接受的答案)。我试图在C++中复制它。当我在main()函数的combos()中输入1,2和5时,它会提供正确的答案,但10会返回11,当它应该是12.我的算法出了什么问题?
#include <iostream>
#include <cstdlib>
using namespace std;
int coin[] = {1, 2, 5, 10, 20, 50, 100, 200};
/*Amounts entered must be in pence.*/
int combinations(int amount, int size) {
int comboCount = 0;
if(amount > 0) {
if(size >= 0 && amount >= coin[size])
comboCount += combinations(amount - coin[size], size);
if(size > 0) //don't do if size is 0
comboCount += combinations(amount, size-1);
} else if(amount == 0)
comboCount++;
return comboCount;
}
int combos(int amount) {
int i = 0;
//get largest coin that fits
for(i = 7; coin[i] > amount && i >= 0; i--);
return combinations(amount, i);
}
int main() {
cout << "Answer: " << combos(10) << endl;
return 0;
}
的可能重复的[suming具体数目的不同方式来获得100](http://stackoverflow.com/questions/6397827/different-ways-of-suming-specific-numbers -to-gain-100) –