lintcode:Fibonacci 斐波纳契数列

题目:

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

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

  • 前2个数是 0 和 1 。
  • 第 i 个数是第 i-1 个数和第i-2 个数的和。

斐波纳契数列的前10个数字是:

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

样例

给定 1,返回 0

给定 2,返回 1

给定 10,返回 34

解题:

好像很简单的。。。递归是最简单的,貌似很耗时,结果:Time Limit Exceeded

Java程序:

递归程序

class Solution {
    /**
     * @param n: an integer
     * @return an integer f(n)
     */
    public int fibonacci(int n) {
        // write your code here
        if(n==1)
            return 0;
        else if(n==2)
            return 1;
        else //if(n>2)
            return fibonacci(n-1) + fibonacci(n-2);
    }
}
View Code

非递归:

class Solution {
    /**
     * @param n: an integer
     * @return an integer f(n)
     */
    public int fibonacci(int n) {
        // write your code here
        if(n==1)
            return 0;
        if(n==2)
            return 1;
        int f0 = 0;
        int f1 = 1;
        int i = 3;
        int f = 0;
        while(i<=n){
            f = f0 + f1;
            f0 = f1;
            f1 = f;
            i++;
        }
        return f;
    }
}
View Code

总耗时: 1176 ms

哦,对了还可以直接根据斐波那契数列公式计算:

Python程序:

class Solution:
    # @param n: an integer
    # @return an integer f(n)
    def fibonacci(self, n):
        # write your code here
        if n==1:
            return 0
        elif n==2:
            return 1;
        f0 = 0
        f1 = 1
        f = 0
        i = 3
        while i<=n:
            f = f0 + f1
            f0 = f1
            f1 = f
            i+=1
        return f 
View Code

总耗时: 205 ms

原文地址:https://www.cnblogs.com/bbbblog/p/4886321.html