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;
    }
}


posted @ 2016-04-08 21:50  phlsheji  阅读(175)  评论(0编辑  收藏  举报