70. Climbing Stairs
Leetcode Dynamic ProgrammingYou 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?
Note: Given n will be a positive integer.
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
分析¶
这道题目考查的是基本的动态规划思想。设想你在楼梯的前i个台阶有numOfWays[i]种走法,那么前i+1个台阶有几种走法。分两种情况,可能此时你站在第i个台阶,那么向前一步即可;也有可能你站在第i-1个台阶,那么向前走两步即可。如果提前知道站在第i个台阶的走法数,和站在第i-1个台阶的走法数,那么把它们相加不就是前i+1个台阶的走法数。也就是
numOfWays[i] = numOfWays[i - 1] + numOfWays[i - 2];
根据上面的关系式,代码就非常简单了。
public int climbStairs(int n) {
int[] numOfWays = new int[n+1];
numOfWays[0] = 1; numOfWays[1] = 1;
for (int i = 2; i < n + 1; i++)
numOfWays[i] = numOfWays[i - 1] + numOfWays[i - 2];
return numOfWays[n];
}
可以不存储中间结果:
public int climbStairs(int n) {
if (n == 1) return 1;
int last = 1, secondLast = 1, now = 0;
for (int i = 2; i < n + 1; i++) {
now = last + secondLast;
secondLast = last;
last = now;
}
return now;
}