Leetcode No.70 Climbing Stairs爬楼梯(c++实现)

1. 题目

https://leetcode.com/problems/climbing-stairs/

2. 分析

以下三种算法的详细介绍参考:https://yyqx.online/posts/leetcode70climbing-stairs/

2.1 自顶向下的递归暴力求解法

具体代码如下:

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

该算法极其简单粗暴,但是时间复杂度为O(\({2}^n\)),时间超时

2.2 自顶向下的记忆优化算法

由于上述算法中计算了大量的重复元素,因此可以用一个map存储这些元素,来节省时间
具体代码如下:

class Solution {
public:
    unordered_map<int, int> cache;//存储已经计算过的climbStairs(n)
    int climbStairs(int n) {
        if (cache.find(n) != cache.end()) { return cache[n]; }//如果已经计算过,则不需要再计算
        int result = 0;
        if (n ==1 || n == 2) { result = n; }
        else { result = climbStairs(n - 1) + climbStairs(n - 2); }
        cache[n] = result;
        return result;
    }
};

代码参考:https://leetcode.com/problems/climbing-stairs/discuss/25315/My-DP-solution-in-C%2B%2B-with-explanation

2.3 自下向上的动态规划算法

具体代码如下:

class Solution {
public:
    int climbStairs(int n) {
        if (n ==1 || n == 2) { return n; }
        int one_step_before = 2;
        int two_steps_before = 1;
        int now_steps = 0;
        for (int i = 3; i <= n; i++) {
            now_steps = one_step_before + two_steps_before;
            two_steps_before = one_step_before;
            one_step_before = now_steps;
        }
        return now_steps;
    }
};

代码参考:https://leetcode.com/problems/climbing-stairs/discuss/25299/Basically-it's-a-fibonacci

posted @ 2021-08-17 10:18  云梦士  阅读(92)  评论(0编辑  收藏  举报