斐波那契矩阵
的算法
1)斐波那契数列的线性求解(O(N))的方式非常好理解
2)同时利用线性代数,也可以改写出另一种表示
| F(N) , F(N-1) | = | F(2), F(1) | * 某个二阶矩阵的N-2次方
3)求出这个二阶矩阵,进而最快求出这个二阶矩阵的N-2次方
// 斐波那契数列算法 f(1)=1,f(2)=1,f(3)=2,f(4)=3,f(5)=5…… o(n)
public static int f(int n) {
if (n < 1) {
return 0;
}
if (n == 1 || n == 2) {
return 1;
}
int res = 1;
int pre = 1;
int tmp = 0;
for (int i = 3; i <= n; i++) {
tmp = res;
res = res + pre;
pre = tmp;
}
return res;
}
// O(logN)的算法 |f(n),f(n-1)| = |f(2),f(1)|*|1,1| ^ (n-2)
// |1,0|
public static int f2(int n) {
if (n < 1) {
return 0;
}
if (n == 1 || n == 2) {
return 1;
}
int[][] baseMatrix = {{1, 1}, {1, 0}};
int[] coefficient = {1, 1};
int[][] res = matrixPower(baseMatrix, n - 2);
return coefficient[0] * res[0][0] + coefficient[1] * res[1][0];
}
public static int[][] matrixPower(int[][] m, int p) {
int[][] res = new int[m.length][m[0].length];
for (int i = 0; i < res.length; i++) {
res[i][i] = 1;
}
// res = 矩阵中的1,矩阵1次方
int[][] t = m;
for (; p != 0; p >>= 1) {
if ((p & 1) != 0) {
res = multiMatrix(res, t);
}
t = multiMatrix(t, t);
}
return res;
}
public static int[][] multiMatrix(int[][] m1, int[][] m2) {
int[][] res = new int[m1.length][m2[0].length];
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m2[0].length; j++) {
for (int k = 0; k < m2.length; k++) {
res[i][j] += m1[i][k] * m2[k][j];
}
}
}
return res;
}
类似斐波那契数列的递归优化(没有条件转移)
如果某个递归,除了初始项之外,具有如下的形式
F(N) = C1 F(N) + C2 F(N-1) + … + Ck * F(N-k) ( C1…Ck 和k都是常数)
并且这个递归的表达式是严格的、不随条件转移的
那么都存在类似斐波那契数列的优化,时间复杂度都能优化成O(logN)
题目
题目1:母牛数量
第一年农场有1只成熟的母牛A,往后的每年:
1)每一只成熟的母牛都会生一只母牛
2)每一只新出生的母牛都在出生的第三年成熟
3)每一只母牛永远不会死
返回N年后牛的数量
public static int cowNumber(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
if (n == 3) {
return 3;
}
int[][] base = {{1, 1, 0}, {0, 0, 1}, {1, 0, 0}};
int[] coefficient = {3, 2, 1};
int[][] res = matrixPower(base, n - 3);
return coefficient[0] * res[0][0] + coefficient[1] * res[1][0] + coefficient[2] * res[2][0];
}
public static int[][] matrixPower(int[][] m, int p) {
int[][] res = new int[m.length][m[0].length];
for (int i = 0; i < res.length; i++) {
res[i][i] = 1;
}
// res = 矩阵中的1,矩阵1次方
int[][] t = m;
for (; p != 0; p >>= 1) {
if ((p & 1) != 0) {
res = multiMatrix(res, t);
}
t = multiMatrix(t, t);
}
return res;
}
public static int[][] multiMatrix(int[][] m1, int[][] m2) {
int[][] res = new int[m1.length][m2[0].length];
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m2[0].length; j++) {
for (int k = 0; k < m2.length; k++) {
res[i][j] += m1[i][k] * m2[k][j];
}
}
}
return res;
}