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

Note: Given n will be a positive integer.

爬楼梯问题,类似于经典的斐波那契数列问题。由于一次只能爬1或者2次楼梯,先从最后一步开始分析,如果最后还有1层楼梯,则有1种办法(1),如果最后还有2层楼梯,则有2种方法(1 + 1)或(2)。然后递归的进行计算即可。

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

这个方法显然会超时,因为递归的写法都可以转换成迭代的写法,以不至于导致超时。用a维护爬楼梯的次数。

class Solution {
public:
    int climbStairs(int n) {
        int a = 1, b = 1;
        while (n--) {
            b = a - b;
            a = a + b;
        }
        return a;
    }
};
// 0 ms

 使用动态规划,dp是一个结果数组,维护每一层所需要的爬楼梯的次数。

class Solution {
public:
    int climbStairs(int n) {
        vector<int> dp(n + 1, 0);
        if (n == 1)
            return 1;
        dp[1] = 1;
        dp[2] = 2;
        for (int i = 3; i != n + 1; i++)
            dp[i] = dp[i - 1] + dp[i - 2];
        return dp[n];
    }
};
// 0 ms
原文地址:https://www.cnblogs.com/immjc/p/7225616.html