解题思路
转移方程:f(n)=f(n-1)+f(n-2),f(n-1)=f(n-1)
[ f ( n ) f ( n − 1 ) ] = [ 1 1 1 0 ] [ f ( n − 1 ) f ( n − 2 ) ] \begin{bmatrix} f(n) \\ f(n-1) \end{bmatrix}= \begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix} \begin{bmatrix} f(n-1) \\ f(n-2) \end{bmatrix} [f(n)f(n−1)]=[1110][f(n−1)f(n−2)]
代码
class Solution {
public:
long* mul(const long* a,const long* b,const int row,const int col,const int kmax) const{
long* ans=new long[row*col];
for(int i = 0;i<row;i++){
for(int j = 0;j<col;j++){
ans[i*col+j]=0;
for(int k = 0;k<kmax;k++){
ans[i*col+j]+=(a[i*kmax+k]*b[k*col+j])%(1000000007);
}
}
}
return ans;
}
int fib(int n) {
if(n==0) return 0;
if(n==1||n==2){
return 1;
}
long* coe=new long[]{1,1,1,0};
long* ans=new long[]{1,1};
n-=2;
while(n){
if(n&1)
ans = mul(coe,ans,2,1,2);
coe = mul(coe,coe,2,2,2);
n>>=1;
}
return ans[0]%1000000007;
}
};