70. Climbing Stairs
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
- 1 step + 1 step
- 2 steps
Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
Constraints:
1 <= n <= 45
跳到某一级有2种方式,从它上一级跳上来,或从它上上级跳上来,所以 f(n)=f(n-1)+f(n-2) 。会超时的递归算法如下,由于涉及到大量的重复运算,时间复杂度 O(an)。
class Solution {
public int climbStairs(int n) {
if(n<=3) return n;
return climbStairs(n-1)+climbStairs(n-2);
}
}
这题的结果是斐波那契数列,每次只需用到前面2个数字,可以将前2个算出的结果存起来,减少重复计算。时间复杂度 O(n)
class Solution {
public int climbStairs(int n) {
if(n<=2) return n;
int pre1=1,pre2=2;
int ret=0;
for(int i=2;i<n;++i){
ret=pre1+pre2;
pre1=pre2;
pre2=ret;
}
return ret;
}
}