算法:斐波那契数列的O(logN)解法
1 class Solution { 2 public: 3 vector<vector<int> > matrixMulti(vector<vector<int> > a,vector<vector<int> > b){ //矩阵乘法 4 vector<vector<int> > rse = {{0,0},{0,0}}; 5 for(int i=0;i!=2;++i){ 6 for(int j=0;j!=2;++j){ 7 for(int k=0;k!=2;++k){ 8 rse[i][j] += a[i][k]*b[k][j]; 9 } 10 } 11 } 12 return rse; 13 } 14 int jumpFloor(int number) { 15 if(number<=2) return number; 16 vector<vector<int> > a = {{1,1},{1,0}}; 17 vector<vector<int> > r = {{1,0},{0,1}}; //单位矩阵 18 int n = number-2; 19 while(n!=0){ 20 if(n&1) 21 r = matrixMulti(a,r); 22 a = matrixMulti(a,a); 23 n >>= 1; 24 } 25 return r[0][0]*2+r[1][0]; 26 } 27 28 };
斐波那契数列:
F(n) = {n n<=2;
{F(n-1)+F(n-2) n>2;
所以每个|F(n),F(n-1) |=|F(n-1),F(n-2)|*{{1,1},{1,0}}
= |F(2),F(1)|*({{1,1},{1,0}})^(n-2)
此时为时间复杂度为O(N);
设a 为矩阵{{1,1},{1,0}}
把number-2看作二进制,假设number-2=7,二进制为111.
a^(n-2)就等于a*(a^2)*(a^4),此时为时间复杂度为O(logN);