🐕 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶
🐖 思路:递归
当n=1 时 返回1
当n=2 时 返回2
当n=3 时 返回3
当n=4 时 返回5
上代码
public static int climbStairs(int n) {
if(n == 1) {
return 1;
}
if(n == 2) {
return 2;
}
return climbStairs(n-1)+climbStairs(n-2);
}
缺点:n 过大时 会超时 因为太多的重复计算
那么就将常规递归换成 尾递归叭~
上代码 (尾递归减少了大量的重复计算)
public static int climbStairsTail(int n) {
return process(n,1,1);
}
public static int process(int n , int a , int b) {
if(n <= 1) {
return b;
}
return process( n - 1 , b , a + b);
}

🐒 思路二:动态规划
上代码
public static int climbStairsDP( int n ) {
if( n == 1) {
return 1;
}
int[] arr = new int[n+1];
arr[1] = 1;
arr[2] = 2;
for(int i = 3 ; i <= n ; i++ ) {
arr[i] = arr[i-1] + arr[i-2];
}
return arr[n];
}

思路三:动态规划 优化版本
DP 优化版本 只需要用两个临时变量即可,不需要申请一个数组
上代码
public static int climbStairsDP_Plus( int n ) {
if( n <= 2) {
return n;
}
int f = 1 , s = 2 , res = 0;
while( n-- > 2) {
res = f + s;
f = s;
s = res;
}
return res;
}

1164

被折叠的 条评论
为什么被折叠?



