一. 斐波那契数列引出矩阵快速幂技巧
斐波那契数列的递推式:F(N) = F(N-1) + F(N-2),二阶递推式
计算矩阵的n-2次方时间复杂度为O(logN)
class Solution {
public int fib(int n) {
if(n == 0)return 0;
if(n== 1 || n==2)return 1;
//假设矩阵从1和2开始,F1=1,F2=1
int times = n-2;
int[][] base = new int[2][2];
base[0][1] =1;
base[0][0] = 1;
base[1][0] = 1;
int[][] res = mutiply(base, times);
return 1*res[0][0] + 1*res[1][0];
}
public int[][] mutiply(int[][] base, int times){
int[][] temp = base;//基
int[][] res = new int[2][2];//先让返回结果等于单位阵
res[0][0] = 1;
res[1][1] = 1;
for(; times != 0; times >>= 1){
if((times & 1) == 1){
res = help(res, temp);
}
temp = help(temp, temp);
}
return res;
}
//矩阵自乘
public int[][] help(int[][] a, int[][] b){
int[][] res = new int[2][2];
for(int i = 0; i < 2; i++){//遍历a的行
for(int j = 0; j < 2; j++){//遍历b的列
for(int k = 0; k < 2; k++){
res[i][j] += a[i][k] * b[k][j];
}
}
}
return res;
}
}
二. 推广到i阶递推式
i阶递推公式都可以通过矩阵快速幂技巧将时间复杂度降为O(logN)
题目一:达标字符串
尝试:
递推函数:F(i),还有i个位置的字符需要填写,返回达标字符串的个数,默认第i-1个位置填写1
1)第k个位置填写1,F(i-1)
2)第k个位置填写0,则第k+1个位置必须填写1,F(i-2)
得到递推公式 F(i) = F(i-1) + F(i-2)
题目二:母牛繁殖问题
一:A
二:A B
三:A B C
四:A B C D
五:A B C D E F
递推式:F(N) = F(N-1) + F(N-3)
F(N-3)表示第N年已经成熟的牛的个数
public static int method(int n) {
int[][] base = new int[3][3];
//[0 1 0]
//[2 0 1]
//[0 0 0]
base[0][1] = 1;
base[1][0] = 2;
base[1][2] = 1;
int[][] res = multiply(base, n-3);
return 3 * res[0][0] + 2 * res[1][0] + res[2][0];
}
public static int[][] multiply(int[][] base, int times){
int[][] res = new int[3][3];
//单位阵
res[0][0]=1;
res[1][1]=1;
res[2][2]=1;
for(;times != 0; times >>= 1){
if((times & 1) == 1){
res = help(res, base);//res * base
}
base = help(base, base);
}
return res;
}
public static int[][] help(int[][] a, int[][] b){
int[][] res = new int[3][3];
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
for(int k = 0; k < 3; k++){
res[i][j] += a[i][k] * b[k][j];
}
}
}
return res;
}
题目三:铺瓷砖问题
假设地板规模为2 * N,一块瓷砖的大小为 1*2,一共有多少种铺瓷砖的方法
F(n) = F(n-1) + F(n-2)