b********d 发帖数: 393 | 1 假设银行有无限量的1分钱,5分钱,10分钱和25分钱的硬币。如果客户给出任意一个取
款数额,求银行总共有几种兑现方法。
例如客户取37分钱。可能的付款方式是:
25+10+1+1
25+5+5+1+1
25+5+1x7
25+1x12
10+10+5+11
.。。。。
试着用递归(recursive function)但是边界条件定义不出来。请高手指点一二,给一
个Pseudo-Code,不胜感激。 | d*****1 发帖数: 1837 | | R*******n 发帖数: 428 | 3 Recursive function is very powerful. Here's my short MATLAB code. rsum
================================================================
function c = rsum(v,m,c)
for i=1:length(v)-1,if v(i)<=m,c=rsum(v(i:end),m-v(i),c);end,end
c = c+1;
================================================================
Then, call this function in MATLAB
c = rsum([25 10 5 1],37,0)
you will get c = 24 for your problem.
More interestingly, if you make the following call
c = rsum([100,50,25,10,5,1],100,0)
you will get the answer for the classical question: How many ways to make
change for a dollar. (c = 293 in this case). You can google "How many ways
to make change for a dollar" to verify the answer. |
|