首页 > 代码库 > LeetCode Climbing Stairs

LeetCode Climbing Stairs

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?




每一次你可以爬一层或者两层,计算爬n层你可以有几种方法。



简单DP问题,但是对于渣渣的不懂DP的我来说还花了很多时间去看了下算法导论的DP问题。


结果借鉴大牛代码算是写了简单的DP代码了:


public class Solution {
    public int climbStairs(int n) {
        if (n == 0 || n == 1) return 1;
        if (n < 0) return 0;
        return climbStairs(n - 1) + climbStairs(n - 2);      
    }
}

递归调用。


可是却超时了,果然正如书上说的,递归的自顶向下数据会爆炸式增长。


我们可以从上式看到斐波拉及数列的影子,所以改用递推:


public class Solution {
    public int climbStairs(int n) {
        if(n==0||n==1)
            return 1;
        int prev = 1;
        int cur = 1;
        for(int i=2;i<=n;i++)
        {
            int temp = prev + cur;
            prev = cur;
            cur = temp;
        }
        return cur;
    }
}


LeetCode Climbing Stairs