首页 > 试题广场 >

有1分,2分,5分,10分四种硬币,每种硬币数量无限,给定n

[问答题]
有1分,2分,5分,10分四种硬币,每种硬币数量无限,给定n分钱,求有多少种组合可以组合成n分钱?
推荐
①,四层循环
②,使用回溯法在空间中搜索
代码为思路: 定义控制台应用程序的入口点。
#include "stdafx.h"

using namespace std;
int count = 0;
int Target = 0;
int coin[4] = {1, 2, 5, 10};
int total = 0;
vector solution;
void dfs(int index)
{
    if ( total == Target )
    {
        count++;
        cout << count << ":" ;
        for ( int i = 0; i < (int)solution.size(); i++)
        {
            cout << solution[i] << " ";
        }
        cout << endl;
        return;
    }
    if ( total > Target )
        return;
    for ( int i = index; i < 4; i++)
    {
        total += coin[i];
        solution.push_back( coin[i] );
        dfs(i);
        solution.pop_back();
        total -= coin[i];
    }
}
int _tmain(int argc, _TCHAR *argv[])
{
    while (1)
    {
        count = 0;
        cin >> Target;
        dfs(0);
        cout << count << endl;
    }
    return 0;
}
编辑于 2015-02-06 14:39:41 回复(0)
这其实也是一个Fibonacci问题
n=1时,就只有1中情况。
n=2时,有2个1分和一个2分两种。
n=3时,有f(2)+f(1)=3种。
n=4时,有f(3)+f(2)=5种。

n=5时,有f(4)+f(3)+1=9种。加1是多了一个5分可选。
6<n<10时,有f(n-1)+f(n-2)+f(n-5)种情况。

n=10时,有f(9)+f(8)+f(5)+1。加1是多了一个10分可选。
n>10时,有f(n-1)+f(n-2)+f(n-5)+f(n-10)种情况。

发表于 2015-09-11 10:23:30 回复(2)