实例:换零钱方式的统计 -- 摘自《计算机程序的构造和解释》

鄙人C++实现,多谢指正:

#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

 

posted @ 2014-09-03 16:18  BornThisWay  阅读(503)  评论(0编辑  收藏  举报