Climbing Stairs

public class Solution {
    public int climbStairs(int n) {
       int res = n - 1;
        if(n == 0){
            return 0;
        }
        int[] mem = new int[n];
        if(n <= 1){
            return 1;
        }
        if(n == 2){
            return 2;
        }
        mem[0] = 1;
        mem[1] = 2;
        for(int i = 2 ; i <= n - 1 ; i++){
            mem[i] = mem[i - 1] + mem[i - 2];
        }
        return mem[res];
    }
}

彷佛是leetcode上面最水的一道題了,不過提交以後竟然Time limit exceed,每當這個時候我就堅決果斷去看discuss,纔想起學校其實也有教上面這種方法(java

The problem here is that you are doing a lot of the work multiple times. For instance, there is no difference between the paths from a given number if you got there by stepping up 1 stair twice or 2 stairs once. The number of ways to get to the top from that stair remains the same, but you are calculating it twice from scratch. Extend that to 4 stairs above your starting point. You could get there using 1-1-1-1, 2-1-1, 1-2-1, 1-1-2, or 2-2. You now need to calculate f(n-4) 4 times.ui

To speed this up, you can remember the result for a given number of steps, then just use that result the next time you need that number instead of recalculating the entire process. This "remembering" is called memoization, and is required for quite a few of the problems on this site in order to complete them before the time limit.this

http://oj.leetcode.com/discuss/2727/climb-stairs-exceed-time-limits-why
code

),固然最開始接觸的是原來的這種會超時的方法:ip

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

才發現雖然作了題目提交了,可是discuss裏面仍是有很多內容能夠看的
leetcode

相關文章
相關標籤/搜索