关闭

[leetcode] 70. Climbing Stairs

标签: leetcodeeasy
82人阅读 评论(0) 收藏 举报
分类:

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



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9803次
    • 积分:633
    • 等级:
    • 排名:千里之外
    • 原创:31篇
    • 转载:150篇
    • 译文:0篇
    • 评论:0条
    文章分类