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,才想起学校其实也有教上面这种方法(

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.

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.

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

),当然最开始接触的是原来的这种会超时的方法:

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值