一 题目
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
二 分析
easy 级别,爬楼梯问题。一个梯子N步,每次走1步或者2步,到顶有多少种走法。实际上一开始也是没看明白。
在纸上画了下,n=1, 1种(1步)
。n=2,2种(1+1;2)
n=3 ,3种(1+1+1、1+2、2+1)
n=4, 5种(1+1+1+1、1+1+2、1+2+1、2+1+1、2+2)
以此类推,会发现这是一个斐波那契数列。设f(n)
表示爬n
阶楼梯的不同方法数,进而分析出:
f(n) = f(n-1)+f(n-2).
2.1 递归
对于斐波那契数列,我们很容易想到了使用递归。
public static int climbStairs(int n) {
if(n==1){
return 1;
}else if(n==2){
return 2;
}else{
return climbStairs(n-1)+climbStairs(n-2);
}
}
但是效率很低, Time Limit Exceeded 。加上缓存数组优化试试。
public static void main(String[] args) {
int res = climbStairs(60);
System.out.println(res);
int res1 = climbStairs(5);
System.out.println(res1);
}
static int[] cache = new int[100];
/**
* 递归+缓存
* @author bohu83
* @param n
* @return
*/
public static int climbStairs(int n) {
if(cache[n-1]!=0){
return cache[n-1];
}
if(n==1){
cache[0] = 1;
return 1;
}else if(n==2){
cache[1] = 2;
return 2;
}else{
cache[n-1] =climbStairs(n-1)+climbStairs(n-2);
return cache[n-1];
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Climbing Stairs.
Memory Usage: 32.8 MB, less than 5.26% of Java online submissions for Climbing Stairs.
2.2 动态规划
上面一开始的递归慢,就是有很多是重复的计算浪费了。而动态规划的提高效率就是依赖之前的结果。
这个状态转移方程原理跟上面的递归一样:dp[i] = dp[i-1] + dp[i-2]
public int climbStairs(int n) {
if(n<=2){
return n;
}
int[] dp = new int[n+1];
dp[1] = 1;
dp[2] = 2;
for(int i=3;i<=n;i++){
dp[i]= dp[i-1]+dp[i-2];
}
return dp[n];
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Climbing Stairs.
Memory Usage: 33.2 MB, less than 5.26% of Java online submissions for Climbing Stairs.
可见dp跟递归+缓存差不多。
当然,最厉害的还是通项公式:
直接算,推导过程我也不懂。