斐波纳契数列的递归与非递归形式

题目

查找斐波纳契数列中第 N 个数。

所谓的斐波纳契数列是指:

前2个数是 01 。
第 i 个数是第 i-1 个数和第i-2 个数的和。
斐波纳契数列的前10个数字是:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

 注意事项

The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.

样例
给定 1,返回 0

给定 2,返回 1

给定 10,返回 34

递归

  public int fibonacci(int n) {
        // write your code here
           if(n == 1){
            return 0;
        }else if(n ==2 || n == 3){
            return 1;
        }else{
           return fibonacci(n - 1)+fibonacci(n -2);
        }

    }

使用递归非常简单,但是非常耗时,在n=41的时候就超时了,所以得使用非递归。

非递归

非递归实现,使用两个中间变量,一个a存fibonacci(n - 2),另一个b存fibonacci(n -1),相加后不断交换,直至循环结束。

  public int fibonacci(int n) {
        // write your code here
           if(n == 1){
            return 0;
        }else if(n ==2 || n == 3){
            return 1;
        }else{
            int sum = 0;
            int a=1,b= 1;
            for(int i = 4;i<= n;i++){
               sum = a+b;
               a= b;
               b = sum;
            }
            return sum;
        }

    }

你可能感兴趣的:(LintCode编程笔记)