[LintCode] Fibonacci

376 查看

Problem

Find the Nth number in Fibonacci sequence.

A Fibonacci sequence is defined as follow:

The first two numbers are 0 and 1.
The i th number is the sum of i-1 th number and i-2 th number.
The first ten numbers in Fibonacci sequence is:

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

Solution


class Solution {
    public int fibonacci(int n) {
        int[] f = new int[n + 2];
        f[1] = 0;
        f[2] = 1;
        for (int i = 3; i <= n; i++) {
            f[i] = f[i - 1] + f[i - 2];
        }
        return f[n];
    }
}
class Solution {
    public int fibonacci(int n) {
        if (n < 3) return n - 1;
        int first = 0;
        int second = 1;
        int third = 1; //its value doesn't matter 
        for (int i = 3; i <= n; i++) {
            third = first + second;
            first = second;
            second = third;
        }
        return third;
    }
}

Recuision 时间浪费太多,不推荐。

class Solution {
    public int fibonacci(int n) {
        if (n == 1) return 0;
        if (n == 2) return 1;
        return fibonacci(n-1) + fibonacci(n-2);
    }
}

还可以用公式实现,我觉得就算了吧。