一、问题简述
这是一个非常经典并且简单的递归问题。给定一个正整数n作为楼梯的阶数,每次可以上一步或者两步,问有几种上楼梯的方法。
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
二、递归方法
开始我是用递归的方法写的,代码很简单,但是时间复杂度很高。
class Solution {
public int climbStairs(int n) {
if(n == 1)
return 1;
if(n == 2)
return 2;
reuturn climbStairs(n - 1) + climbStairs(n - 2);
}
}
三、动态规划
改用动态规划后,时间复杂度就可以降下来了。观察发现,实际上我们计算第n步的时候,只用到了n-1步和n-2步,所以,我们只需要一个长度为2的数组,保存前两步的上楼梯方法即可。
class Solution {
public int climbStairs(int n) {
int[] steps = new int[2];
steps[0] = 1;
steps[1] = 2;
for(int i = 3;i <= n;i ++){
if(i % 2 == 1)
steps[0] += steps[1];
else
steps[1] += steps[0];
}
if(n % 2 == 1)
return steps[0];
return steps[1];
}
}