零钱问题

来源:互联网 发布:opendds 数据丢包 编辑:程序博客网 时间:2024/04/29 14:59

有1块,2块,5块,10块,20块,50块,100块,200块这几种面值的货币,问总共有多少种组合出200块的方法?

循环穷举是通常首先想到的办法

int count=0;
int a, b, c, d, e, f, g;
for( a=200 ; a>=0 ; a -= 200 )
for( b=a ; b>=0 ; b -= 100 )
for( c=b ; c>=0 ; c -= 50 )
for( d=c ; d>=0 ; d -= 20 )
for( e=d ; e>=0 ; e -= 10 )
for( f=e ; f>=0 ; f -= 5 )
for( g=f ; g>=0 ; g -= 2 )
count++;

1块钱的循环是可以省去的。

想用递归来解一直都没有成功,后来看了别人的代码,终于明白了。其实很简单,贴出来给大家共享,顺便鄙视下自己,递归还得好好学。。。

//以下为摘抄代码

int coins[8] = {200, 100, 50, 20, 10, 5,2,1};
 
int ways(int money, int maxcoin)
{
    int sum = 0;
    if(maxcoin == 7) return 1;
    for(int i = maxcoin; i<8;i++)
    {
        if (money-coins[i] == 0) sum+=1;
        if (money-coins[i] > 0) sum+=findposs(money-coins[i], i);
    }
    return sum;    
}


int main()
{
    cout<<findposs(200, 0)<<endl;
}

原创粉丝点击