方法一. 递推?
class Solution {
public:
int fib(int n) {
int MOD = 1e9 + 7;
if (n < 2) return n;
int p = 0, q = 0, r = 1;
for (int i = 2; i <= n; i++) {
p = q;
q = r;
r = (p + q) % MOD;
}
return r;
}
};
方法二:矩阵快速幂
class Solution {
public:
const int MOD = 1e9 + 7;
int fib(int n) {
if (n < 2) return n;
vector<vector<long>> q{{1, 1},{1, 0}};
vector<vector<long>> res = pow(q, n - 1);
return res[0][0];
}
// 快速幂:利用二进制表示法,将高次幂转化成二进制位为1处对应的各低次幂的乘积。
vector<vector<long>> pow(vector<vector<long>>& a, int n) {
vector<vector<long>> ret{{1, 0}, {0, 1}}; // 单位阵
while (n) {
if (n & 1) {
ret = mutiply(ret, a);
}
n >>= 1;
a = mutiply(a, a);
}
return ret;
}
// 定义矩阵乘法
vector<vector<long>> mutiply(vector<vector<long>> &a, vector<vector<long>> &b) {
vector<vector<long>> c{{0, 0}, {0, 0}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
c[i][j] = (a[i][0] * b[0][j] + a[i][1] * b[1][j]) % MOD;
}
}
return c;
}
};
?