根据递推公式构造系数矩阵用于快速幂(竞赛中经常用到)
进阶博客:https://blog.csdn.net/u012061345/article/details/52224623#commentBox
class Mat { // 矩阵对象 int n = 2; int m[][] = new int[n][n]; public Mat mul(Mat a) { // 矩阵乘法 Mat b = new Mat(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) b.m[i][j] += this.m[i][k] * a.m[k][j]; } return b; } } public class Solution { public int JumpFloor(int target) { if(target==0){ return 0; } Mat ans = new Mat(); for (int i = 0; i < ans.n; i++) { //单位矩阵初始化 ans.m[i][i] = 1; } Mat base = new Mat(); base.m[0][0] = base.m[0][1] = base.m[1][0] = 1; // base矩阵初始化 base.m[1][1] = 0; target -= 1; while (target > 0) { // 快速幂:求base矩阵的n-1次方 if ((target & 1) != 0) { ans = ans.mul(base); } target >>= 1; base = base.mul(base); } return ans.m[0][0]+ans.m[0][1]; } }