Loading

Leetcode-509-矩阵快速幂斐波那契

题目链接


如题目
f[0] = 0
f[1] = 1
f[n] = f[n-1] + f[n-2]

要求

时间复杂度 O(logn)

思路

矩阵快速幂,
和快速幂一样,只是把乘数换成矩阵。
本题数据小,不需要取模


C++代码

class Solution {
public:
    int fib(int n)
    {
        if (n < 2) return n;
        vector<vector<int>> ans={{1,1},{1,0}};
        ans = matrix_pow(ans,n-1);
        return ans[0][0];
    }

    vector<vector<int>> multiply(vector<vector<int>>& a, vector<vector<int>>& b)
    {
        int n = a.size();
        vector<vector<int>> ans(n, vector<int>(n));
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                for (int k = 0; k < n; k++)
                    ans[i][j] += a[i][k]*b[k][j];
        return ans;
    }
    vector<vector<int>> matrix_pow(vector<vector<int>> &a, int b)
    {
        int n = a.size();
        vector<vector<int>> ans(n, vector<int>(n));
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (i==j)
                    ans[i][j] = 1;
        while (b)
        {
            if (b&1)
                ans = multiply(ans, a);
            b >>= 1;
            a = multiply(a, a);
        }
        return ans;
    }
};
posted @ 2022-01-19 23:33  ARUI丶  阅读(54)  评论(0编辑  收藏  举报