题目描述

https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof/

解题思路

112 斐波那契-快速幂 - 图1

  1. class Solution {
  2. public:
  3. vector<vector<long>> matmul(vector<vector<long>>& mat, int num) {
  4. if (num==1)
  5. return mat;
  6. vector<vector<long>> a=matmul(mat, num / 2);
  7. vector<vector<long>> b=matmul(mat, num - num / 2);
  8. long c00=(a[0][0]*b[0][0] + a[0][1]*b[1][0])%1000000007;
  9. long c01=(a[0][0]*b[0][1] + a[0][1]*b[1][1])%1000000007;
  10. long c10=(a[1][0]*b[0][0] + a[1][1]*b[1][0])%1000000007;
  11. long c11=(a[1][0]*b[0][1] + a[1][1]*b[1][1])%1000000007;
  12. return vector<vector<long>>{{c00, c01}, {c10, c11}};
  13. }
  14. int fib(int n) {
  15. if (n < 2)
  16. return n;
  17. vector<vector<long>> mat{{1,1},{1,0}};
  18. vector<vector<long>> coff=matmul(mat, n-1);
  19. int ret=coff[0][0];
  20. return ret;
  21. }
  22. };