[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?

Solution 1

idea: recursive function, however, run out of limit time

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

Solution 2

idea: similar to Fibonacci number

class Solution {
public:
    int climbStairs(int n) {
        if (n==1)
            return 1;
        else if (n==2)
            return 2;
        else{
            int ppre = 1;
            int pre = 2;
            for (int i = 3; i < n; i++){
                int tmp = pre;
                pre = ppre+pre;
                ppre = tmp;
            }
            return pre+ppre;
        }
        
    }
};



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/denny851108/article/details/51565477
文章标签: leetcode easy
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

[leetcode] 70. Climbing Stairs

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭