Tail recursive Fibonacci number

 

First, the Fibonacci number

The Fibonacci a column refers to a number of columns 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765 , 10946,17711,28657,46368 ......

 

Second, recursive algorithm

1. Code

public int fib(int n){
      if(n==1 || n==2){
            return 1;
      }

      return fib(n-1)+fib(n-2);
}

2. Disadvantages: calculated repeated a plurality of times fib (n), low-performance, general recursive algorithm for illustration only

 

Third, improvements: space for time, the calculated fib (n) stored without double counting, the spatial complexity is O (n)

public int fib(int n){
       int[] array=new int[n];
       array[0]=1;
       array[1]=1;

       for(int i=2;i<n;i++){
           array[i]=array[i-1]+array[i-2];
        }

       return array[n-1];
}

 

Fourth, again improved, to reduce the space O (1), stores only the number 3: The first two numbers and the first two numbers calculated from the sum of the results

public int fib(int n){
       int first=1;
       int second=2;
       int third=3;

       for(int i=3;i<=n;i++){
           third=first+second;
           first=second;
           second=third;
       }

       return third;
}

 

Fifth, tail recursion

public int fib(int n,int first,int second){
      if(n<=1){
          return first;
      }

      rerurn fib(n-1,second,first+second);
}

 

 

 

reference:

https://www.cnblogs.com/andy-songwei/p/11707142.html

 

Guess you like

Origin www.cnblogs.com/june0816/p/6265623.html