递归-斐波那契(母牛生小牛问题)

题:

   若一头小母牛,从出生起第四个年头开始每年生一头母牛,按此规律,第n年有多少头母牛?
具体分析:
1.分析题目:(从出生起第四个年头开始每年生一头母牛)
时间(年) 未成熟母牛(头) 成熟母牛(头) 母牛总数(头)
1   1      0   1
2   1      0   1
3   1      0   1
4   0      1   1
5   1      1   2
6   2      1   3
7   3      1   4
8   3      2   5
9   4      3   7
10   6      4   10
从图中可以看出A1=1,A2=2,A3=3,A4=4,A5=A4+A1等,则依此规律,An=An-1+An-4.这个规律很重要的,因为我们可以从中得到类似问题的规律(例如:从出生起第m个年头开始每年生一头母牛,则得到的规律是Fn=Fn-1+Fn-m (n>m)).

递归算法:

None.gif // 递归
None.gif
     public   static   int  GetCowRecursive( int  year)
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif {
InBlock.gif        
int result=0;
InBlock.gif            
if(year>4)
InBlock.gif                result
=GetCowRecursive(year-1)+GetCowRecursive(year-4);
InBlock.gif            
else    
InBlock.gif                result
=1;    
InBlock.gif        
return result;        
ExpandedBlockEnd.gif    }

None.gif    
// 非递归
None.gif
     public   static   int  GetCow( int  year)
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif {
InBlock.gif        
int f1=1;
InBlock.gif        
int f2=1;
InBlock.gif        
int f3=1;
InBlock.gif        
int f4=1;
InBlock.gif        
int fib=0;
InBlock.gif        
if(year>4)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
for(int i=5;i<=year;i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif            fib
=f4+f1;
InBlock.gif            f1
=f2;
InBlock.gif            f2
=f3;
InBlock.gif            f3
=f4;
InBlock.gif            f4
=fib;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return fib;
ExpandedSubBlockEnd.gif        }

InBlock.gif        
else
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return 1;
ExpandedSubBlockEnd.gif        }

ExpandedBlockEnd.gif    }

转载于:https://www.cnblogs.com/solo/archive/2008/02/02/1062465.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值