递归算法

普通的算法:
 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 = 1return 1; }
            
else
            {

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

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

posted @ 2011-05-11 18:04  小小部落  阅读(210)  评论(0编辑  收藏  举报