LeetCode(70)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?


分析如下:

看到这里这段评论写得挺好,就直接贴过来了。This is just Fibonacci numbers. The number of distinct ways for n steps are the sum of distinct ways for n-1 (because we can move 1 step first, then move the rest n - 1 steps) and distinct ways for n - 2 (because we can move 2 steps first, there are two ways to do it: move 1 steps twice and move 2 steps once, the former is a duplicate for the n - 1 case so we should eliminate).


代码如下:

class Solution {
public:
    int climbStairs(int n) {
        int a1=1;
        int a2=2;
        int sum=0;
        if(n==1)
            return 1;
        if(n==2)
            return 2;
        for(int i=3;i<=n;i++){
            sum=a1+a2;
            a1=a2;
            a2=sum;
        }
        return sum;
    }
};

小结:

(1) 本题需要先想想画画,明白题目的本质是斐波那契数列求通项公式的问题。我先一开始用递归,提交发现超时。考虑到递归会比迭代增加更多的时间和空间开销,所以就改为递归,程序就通过了。

2014-10-06 update: 

本质和上面一样,只是updae后用数组steps来储存结果,比上面用a1, a2, sum轮流存储的方式易读一些。

class Solution {
public:
    int climbStairs(int n) {
        int* steps = new int[n + 1];
        steps[1] = 1;
        steps[2] = 2;
        for (int i = 3; i <= n; ++i) {
            steps[i] = steps[i - 1] + steps[i - 2];
        }
        return steps[n];
    }
};

和这道题目比较像 。 Leetcode (94) Unique Binary Search Trees 



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值