题目:有半美元,1/4美元,10美分,5美分,1美分的硬币,将1美元换成硬币,有多少种不同方式?
题目:有半美元,1/4美元,10美分,5美分,1美分的硬币,将1美元换成硬币,有多少种不同方式?
分析:看到题目,我们可能首先想到贪心法或者动态规划,现在我们换一种思路,尝试用函数式编程的思想,具体思路如下:
假定可用的硬币已经排了某种顺序(从大到小),于是就有以下关系:
将总数为a现金换成n种硬币的不同方式的数目等于:
1.将现金数a换成除第一种硬币之外的所有其他硬币的不同方式数目,加上
2.将现金数a-d换成所有种类的硬币的不同方式数目,其中的d是第一种硬币的币值
这种方法的正确性:1和2可以看成两种分类,1里都没有使用第一种硬币,2里都使用了第一种硬币(至少使用了一个第一种的),1并2为全集,所有的情况都考虑了进来。
如此这般问题递归地归约为对更少现金数或者更少种类硬币的同一个问题。
而特殊情况如下:
1.如果a就是0,应该算作是有一种换零钱的方式
2.如果a小于0,应该算作是有0种换零钱的方式
3.如果n是0,应该算作是有0种换零钱的方式
c语言代码:
#include <stdio.h>
int first(int k)
{
if(k==1) return 1;
if(k==2) return 5;
if(k==3) return 10;
if(k==4) return 25;
if(k==5) return 50;
}
int cc(int amount,int kindOfCoins)
{
if(amount==0) return 1;
if(amount<0||kindOfCoins==0) return 0;
return cc(amount,kindOfCoins-1)+cc(amount-first(kindOfCoins),kindOfCoins);
}
int count_change(int amount)
{
int times;
times=cc(amount,5);
return times;
}
int main()
{
printf("%d\n",count_change(100));
return 0;
}
运行结果
end![再见](http://static.blog.csdn.net/xheditor/xheditor_emot/default/bye.gif)
![再见](http://static.blog.csdn.net/xheditor/xheditor_emot/default/bye.gif)
![再见](http://static.blog.csdn.net/xheditor/xheditor_emot/default/bye.gif)
![再见](http://static.blog.csdn.net/xheditor/xheditor_emot/default/bye.gif)
![再见](http://static.blog.csdn.net/xheditor/xheditor_emot/default/bye.gif)