【问题标题】:Project Euler #31欧拉计划 #31
【发布时间】:2011-07-19 21:58:38
【问题描述】:

问题描述:

在英格兰,货币由英镑、£ 和便士、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;
}

【问题讨论】:

标签: c++ coin-change


【解决方案1】:

那么,您的代码可能会返回 11,因为这是正确的答案?

【讨论】:

  • 是的。这就是我通过手工和程序得到的。
  • 哎呀...是的,显然 10 种可能性只有 11 种。
【解决方案2】:

(实际上是评论):抱歉,我只看到 1、2 和 5 中 10 便士的 10 种组合:

10p:    0..5*2p + rest*1p     : 6 combinations
1x5p + 5p, that is
        0..2*2p + rest*1p     : 3 combinations
        1*5p                  : 1 combination

【讨论】:

  • 1x10p 硬币计数,以及 5x2p 硬币。
  • 您也可以使用一个 10 便士硬币,总共 11 种方式。
  • 对,如果还有10便士的硬币,那就再加一个组合。 (最后的组合其实是 2x5p)
猜你喜欢
  • 2012-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多