[LeetCode] 509. Fibonacci Number

Description

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0,   F(1) = 1
F(N) = F(N - 1) + F(N - 2), for N > 1.

Given N, calculate F(N).

Example 1:

Input: 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 2:

Input: 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

Example 3:

Input: 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

Note:

0 ≤ N ≤ 30.

Analyse

Fibonacci数

F(0) = 0,   F(1) = 1
F(N) = F(N - 1) + F(N - 2), for N > 1.

可以很快地写出一个递归的版本,时间复杂度为\(O(n^2)\)

画出递归树

但递归的版本会很慢,而且会产生很多重复计算

int fib(int N) {
    if (N <= 1) return N;
    return fib(N-1) + fib(N-2);
}

尾递归优化版本

如果一个函数中所有递归形式的调用都出现在函数的末尾,我们称这个递归函数是尾递归的。当递归调用是整个函数体中最后执行的语句且它的返回值不属于表达式的一部分时,这个递归调用就是尾递归。尾递归函数的特点是在回归过程中不用做任何操作,这个特性很重要,因为大多数现代的编译器会利用这种特点自动生成优化的代码。

时间复杂度\(O(n)\)

int fib(int first, int second, int N)
{
    if (N < 3)
    {
        return 1;
    }
    if (N == 3)
    {
        return first + second;
    }

    return fib(second, first + second, N-1);
}

把递归改成循环,时间复杂度\(O(n)\)

int fib(int N)
{
    if (N < 2) {return N;}

    int first = 0;
    int second = 1;
    int sum = 0;

    while (--N)
    {
        sum = first + second;
        first = second;
        second = sum;
    }

    return sum;
}

动态规划(不确定算不算),用个数组存储已经计算过的结果

int fib(int N)
{
    int *vec = new int[N+1];
    vec[0] = 0;
    vec[1] = 1;

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

    return vec[N];
}

Reference

  1. 斐波那契时间复杂度和空间复杂度分析
posted @ 2019-01-17 20:15  arcsinW  阅读(393)  评论(0编辑  收藏  举报