leetcode 509斐波那契数列

递归方法:

时间O(2^n),空间O(logn)

class Solution {
public:
    int fib(int N) {
        return N<=1?N:fib(N-1)+fib(N-2);
    }
};

递归+记忆化搜索:

时间O(n),空间O(logn)

class Solution {
public:
    vector<int> dp={0,1};

    int fib(int N) {
        if(N<=1) return N;
        if(N>=dp.size()){
            int x=fib(N-1)+fib(N-2);
            dp.push_back(x);
        }
        return dp[N];
    }
};

动态规划:

时间O(n),空间O(n)

class Solution {
public:
    vector<int> dp={0,1};

    int fib(int N) {
        if(N<=1) return N;
        for(int i=2;i<=N;i++){
            int x=dp[i-1]+dp[i-2];
            dp.push_back(x);
        }
        return dp[N];
    }
};

改进版动态规划:

时间O(n),空间O(1)

class Solution {
public:
    int fib(int N) {
        if(N==0) return 0;
        int a=0,b=1;
        while(N>=2){
            int tmp=b;
            b=a+b;
            a=tmp;
            N--;
        }
        return b;
    }
};

数学方法:直接通过矩阵运算算出来,参见《算法设计指南》待补充

也可参考leetcode 解答:https://leetcode-cn.com/articles/climbing-stairs/

原文地址:https://www.cnblogs.com/joelwang/p/10816137.html