剑指offer 9. 斐波那契数列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaohaibo_/article/details/85544544

输入一个整数 n ,求斐波那契数列的第 n 项。
假定从0开始,第0项为0。(n<=39)
样例

输入整数 n=5 
返回 5

滚动数组
时间复杂度 O ( n ) O(n) ,空间复杂度 O ( 1 ) O(1)

class Solution {
public:
    int Fibonacci(int n) {
        // 0 1 1 2 3 5
        int num[2];
        num[0] = 0;
        num[1] = 1;
        for(int i = 2; i <= n; ++ i)
            num[i % 2] = num[0] + num[1];
        return num[n % 2];
    }
};

矩阵快速幂
时间复杂度 O ( l o g n ) O(logn)
待补

猜你喜欢

转载自blog.csdn.net/zhaohaibo_/article/details/85544544