递归算法

普通的算法:
  class  Program
    {
        
// 首先碰到的是这样的一首题目:计算数组{1,1,2,3,5,8.......} 第30位值,不用递归,我写出了以下这样的代码
         static   void  Main( string [] args)
        {

            
// 分析 
             /* 第一位不管它,因为第一位是没得加的
             * 第二位是第一位+0
             * 第三位是第二位+第一位
             * 所以我一般的想法是:
             * 
*/
            
int  returnInt  =   0 ;
            
int  lastlast  =   1 ;
            
int  lastInt  =   1 ;
            
for  ( int  i  =   1 ; i  <=   30 ; i ++ )
            {
                
if  (i  ==   1 || i==2 ) { returnInt  =   1 ; lastlast  =   1 ; lastInt  =   1 ; }
                
else
                {
                    
                    returnInt 
=  Sub(lastInt, lastlast);
                    lastlast 
=  lastInt;
                    lastInt 
=  returnInt;
                   
                }

                Console.WriteLine(returnInt);
            }


            Console.Read();
        }

     
static    int  Sub( int  i,  int  j)
        {
            
return  i  +  j;
        }
    }

 

 

结果是:

 

1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040

 

 

如果用递归,则是:

 

     class  Program
    {
        
// 首先碰到的是这样的一首题目:计算数组{1,1,2,3,5,8.......} 第30位值,不用递归,我写出了以下这样的代码
         static   void  Main( string [] args)
        { 

            Console.WriteLine(Sub(
30 ));
            Console.Read();
            
        }

        
static   int  Sub( int  i)
        {

            
// 递归法 
             if  (i  ==   1   ||  i  ==   2 ) { returnInt  =   1 ; lastlast  =   1 ; lastInt  =   1 return   1 ; }
            
else
            {

                
return  Sub(i  -   1 +  Sub(i  -   2 );
            } 
        }
    }

结果是:次数是1664079; the values is 832040

转载于:https://www.cnblogs.com/aaa1028/archive/2011/05/11/2043480.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值