實例:換零錢方式的統計 -- 摘自《計算機程序的構造和解釋》

鄙人C++實現,多謝指正:ios

#include <iostream>
using namespace std;

int HuanLingQian(int);
int HuanLingQian(int, int);

// 零錢種類
const int KINDS_OF_COINS = 5;
int kindsOfCoins[KINDS_OF_COINS] = {1, 5, 10, 25, 50};

int _tmain(int argc, _TCHAR* argv[])
{
    // 假如須要把1美圓(100美分)換成零錢
    int amount = 100;

    cout << HuanLingQian(amount) << endl;

    cin.get();

    return 0;
}

int HuanLingQian(int amount)
{
    return HuanLingQian(amount, KINDS_OF_COINS);
}

int HuanLingQian(int amount, int coinKinds)
{
    if (amount == 0)
    {
        return 1;
    } 
    else if (amount < 0 || coinKinds == 0)
    {
        return 0;
    }
    else
    {
        return HuanLingQian(amount, coinKinds - 1) + HuanLingQian(amount - kindsOfCoins[coinKinds - 1], coinKinds);
    }
}
View Code
相關文章
相關標籤/搜索