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?
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
动态规划问题,爬楼梯类似于斐波那契数列
1 | 1 | 1 | |||||||
2 | 2 | 1+1 | 2 | ||||||
3 | 3 | 1+1+1 | 2+1 | 1+2 | |||||
4 | 5 | 1+1+1+1 | 2+1+1 | 1+2+1 | 1+1+2 | 2+2 | |||
5 | 8 | 1+1+1+1+1 | 2+1+1+1 | 1+2+1+1 | 1+1+2+1 | 2+2+1 | 1+1+1+2 | 2+1+2 | 1+2+2 |
每次爬楼梯的方法数是上一次的方法数每一个加1,或者上上次的方法数每一个加2,最终结果是上次的方法数和上上次的方法数相加之和。
使用递归的方法:
class Solution {
public int climbStairs(int n) {
if(n==1) return 1;
if(n==2) return 2;
return climbStairs(n-1) + climbStairs(n-2);
}
}
不使用递归的动态规划方法,使用数组保存子问题的最优解,状态转移公式为f(n) = f(n-1) + f(n-2)
class Solution {
public int climbStairs(int n) {
int[] arr = new int[n+1];
arr[0] = 1;
arr[1] = 1;
for(int i=2; i<=n; i++){
arr[i] = arr[i-1] + arr[i-2];
}
return arr[n];
}
}