具体方式请参考《算法导论》课程(开始于29分30秒):
https://www.bilibili.com/video/av11928034/?p=3
class Solution {
public:
struct Matrix {
int a11, a12, a21, a22;
};
Matrix mul(Matrix m1, Matrix m2) {
return {
m1.a11 * m2.a11 + m1.a12 * m2.a21, m1.a11 * m2.a12 + m1.a12 * m2.a22,
m1.a21 * m2.a11 + m1.a22 * m2.a21, m1.a21 * m2.a12 + m1.a22 *m2.a22
};
}
Matrix pow(Matrix m, int n) {
if(n == 0) return {
1, 0,
0, 1
};
auto temp = pow(m, n / 2);
temp = mul(temp, temp);
if(n % 2) temp = mul(temp, m);
return temp;
}
int Fibonacci(int n) {
if(n == 0) return 0;
if(n == 1) return 1;
Matrix m = {
0, 1,
1, 1
};
auto temp = pow(m, n - 1);
return temp.a22;
}
};
这个应该是最快的解法了?