版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26440803/article/details/80891404
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?
解析:台阶问题,每次可以走一步或者两部,问第n个台阶有多少种走法。
解法一:使用递归,不过数字大了会超时
从当前台阶开始,每次走一步或者走两步直至到大台阶为0时结束
- 代码
static int count = 0;
public static void climbStairs(int n) {
if(n < 0 ) return ;
if(n == 0) {count++;return;}
climbStairs(n-1);
climbStairs(n-2);
}
解法二:使用动态规划
由题意可知,要想到达n阶台阶,可以从N-1台阶走一步到达,可以从N-2台阶走两步到达:
dp[i] 代表是i阶台阶的可走方案数。
递推公式
dp[i] = dp[i-1] + dp[i-2]
。
需要初始化dp[0] dp[1] dp[2];
- 代码
public static void climbStairs(int n) {
if(n <= 2) return n;
int dp[] = new int[n+1];
dp[0] = 0;
dp[1] = 1;
dp[2] = 2;
for(int i =3 ; i<= n ; i++) {
dp[i] = dp[i-1]+dp[i-2];
}
return dp[n];
}