climbing-stairs-动态规划,爬楼梯的路径数

时间:2022-01-08 05:32:23

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

现在说一下大致思路:求出递推公式

f(n)=f(n-1)+f(n-2) ===>f(n)+f(n-1)=2f(n-1)+f(n-2)

[f(n) f(n-1)]=[[1 1][1 0]][f(n-1) f(n-2)]

可以得到递推矩阵

所以该算法的关键点就是:1.需要求出递推矩阵;2.写一个方法,能够实现矩阵相乘

虽然代码量会比其他几个方法大,但是算法复杂度比较低

* 动态规划解法
*/
public int climbStairs3(int n) {
if (n <= )
return ;
if (n == )
return ;
if (n == )
return ; int[][] base = { { , }, { , } };
int[][] res = matrixPower(base, n - ); return *res[][] + res[][];
}
/*
* 两个矩阵相乘
*/
private int[][] muliMatrix(int[][] m1, int[][] m2) {
int[][] res = new int[m1.length][m2[].length];
for (int i = ; i < m1.length; i++) {
for (int j = ; j < m2[].length; j++) {
for (int k = ; k < m2.length; k++) {
res[i][j] += m1[i][k] * m2[k][j];
}
}
}
return res;
}

包含三种最常用的回答,第一最优,第三最差

* 空间复杂度O();
*/
public int climbStairs(int n) {
if (n < )
return n;
int one_step_before = ;
int two_steps_before = ;
int all_ways = ;
for (int i = ; i < n; i++) {
all_ways = one_step_before + two_steps_before;
two_steps_before = one_step_before;
one_step_before = all_ways;
}
return all_ways;
}
/*
* 空间复杂度O(n);
*/
public int climbStairs_2(int n) {
if (n < )
return n;
int[] res = new int[n + ];
res[] = ;
res[] = ;
for (int i = ; i <= n; i++) {
res[i] = res[i - ] + res[i - ];
}
return res[n];
}
/*
* 方法一:递归 时间复杂度高
*/
public int climbStairs_1(int n) {
if (n < )
return ;
if (n == )
return ;
if (n == )
return ;
return climbStairs_1(n - ) + climbStairs_1(n - );
}

斐波那契数列

class Solution {
public:
int climbStairs(int n) {
int f = ;
int g = ;
while(n--){
f += g;
g = f -g;
}
return f;
}
};