1、题目
一个人可以一次往上迈 1 级台阶,也可以迈 2 级台阶,返回这个人迈上 n 级台阶的方法数。
2、思路
对于 n 级台阶,如果第一次迈 1 级台阶,那么问题就变成了迈上 n - 1 级台阶的方法数;同理,如果第一次迈 2 级台阶,问题就变成了迈上 n - 2 级台阶的方法数。因为只有这两种上台阶的方法,所以 F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)F(n)=F(n−1)+F(n−2),这也是个斐波那契数列,有 O(logn)O(logn)O(logn) 的解法:
public class ClimbStair {
//暴力递归的方法
public static int s1(int n) {
if (n < 1) {
return 0;
}
if (n == 1 || n == 2) {
return n;
}
return s1(n - 1) + s1(n - 2);
}
//递推的方法
public static int s2(int n) {
if (n < 1) {
return 0;
}
if (n == 1 || n == 2) {
return n;
}
int res = 2;
int pre = 1;
int tmp = 0;
for (int i = 3; i <= n; i++) {
tmp = res;
res = res + pre;
pre = tmp;
}
return res;
}
//logn的解法
public static int s3(int n) {
if (n < 1) {
return 0;
}
if (n == 1 || n == 2) {
return n;
}
int[][] base = { { 1, 1 }, { 1, 0 } };
int[][] res = matrixPower(base, n - 2);
return 2 * res[0][0] + 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; //对角线为1
}
// res = 矩阵中的1
int[][] t = m;// 矩阵1次方
for (; p != 0; p >>= 1) { //右移
if ((p & 1) != 0) { //p&1得到次方的二进制形式最后1位,如果为1表示当前的值需要
res = product(res, t);
}
t = product(t, t);
}
return res;
}
// 两个矩阵乘完之后的结果返回
public static int[][] product(int[][] a, int[][] b) {
int n = a.length;
int m = b[0].length;
int k = a[0].length; // a的列数同时也是b的行数
int[][] ans = new int[n][m];
for(int i = 0 ; i < n; i++) {
for(int j = 0 ; j < m;j++) {
for(int c = 0; c < k; c++) {
ans[i][j] += a[i][c] * b[c][j];
}
}
}
return ans;
}
}