面試題精選(70):100人民幣問題

來源:互聯網
上載者:User

題目描述:

用1元,2元,5元,10元,20元和50元的紙幣組成100元,共有多少種情況。
要求輸出總方案數和每種方案中各紙幣的個數。

 

////////////////////////////4562種

 

代碼:

背包解法:

 #include <iostream>
using namespace std;

#define N 6

int w[N];
int number_used[N];
//bool is_used[N];
int countnum=0;

void init()
{
    w[0] = 1;
    w[1] = 2;
    w[2] = 5;
    w[3] = 10;
    w[4] = 20;
    w[5] = 50;
    for (int i = 0; i < N; i++)
    {
        number_used[i] = 0;
    }
}

void test(int start_index, int left_weight)
{
    if (left_weight == 0)
    {
        for (int i = 0; i < N; i++)
        {
            if (number_used[i] > 0) cout << w[i] << "元: "<< number_used[i] <<"張 ";
        }
        cout << endl;
        countnum++;
    }
    for (int i = start_index; i < N; i++)
    {
        if (left_weight >= w[i])
        {
            number_used[i]++;
            test(i, left_weight - w[i]);
            number_used[i]--;
        }
    }
}

int main()
{
    init();

    test(0, 100);
    cout<<countnum<<endl;
    system("pause");
    return 0;
}

 

 

另外一種遞迴求總數解法:

const int v[6] = {1,2,5,10,20,50};

int f(int n, int w)
{
    if(n<0) return 0;
    if(n==0) return 1;
    if(w<0) return 0;

    return f(n, w-1) + f(n-v[w], w);
}

void main()
{
    cout<<f(100,5)<<endl;

    system("pause");
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.