首页 > 其他 > 详细

LeetCode 70 Climbing Stairs

时间:2015-11-17 10:35:59      阅读:195      评论:0      收藏:0      [点我收藏+]

LeetCode 70 Climbing Stairs

 

使用递归方法,超时

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); //最后必然是通过1步或者2步到达第n层 
}

 

非递归方法,和斐波那契数列类似:

斐波拉切数列:1、1、2、3、5、8、13、21、……在数学上,其被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2)

int climbStairs(int n) {
    if (n == 0 || n == 1)
      return 1;
    int pre = 1;
    int current = 1;
    for (int i = 2; i <= n; i++) {
      int temp = current + pre;
      pre = current;
      current = temp;
    }
    return current;
}

 

LeetCode 70 Climbing Stairs

原文:http://www.cnblogs.com/walker-lee/p/4970801.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!