题目:

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?

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

分析:

每次可以爬1阶或2阶,求爬n阶楼梯有多少种爬法。

我们知道要爬到第n阶,可以由第n-1阶爬1阶和第n-2阶爬2阶完成,所以f(n) = f(n-1) + f(n-2)。但使用递归会超时。

我们可以开辟一个大小为n+1的数组nums,nums[i]表示爬到第i阶有多少中爬法,依据前面的公式可以求出。

此外我们可以定义f,s,res三个变量来代替数组,因为实际上在求第i阶有多少种爬法时,只与i-1和i-2有关,所以我们可以用f表示前一个楼梯爬的个数,s表示后一个楼梯爬的个数,res表示当前求的,没求一次,更新一下f,s的值即可。

程序:

class Solution {
public:
    int climbStairs(int n) {
        if(n == 1) return 1;
        if(n == 2) return 2;
        int f = 1, s = 2, res = 0;
        for(int i = 3; i <= n; ++i){
            res = f + s;
            f = s;
            s = res;
        }
        return res;
    }
};
// class Solution {
// public:
//     int climbStairs(int n) {
//         vector<int> nums(n+1);
//         nums[0] = 1;
//         nums[1] = 1;
//         for(int i = 2; i <= n; ++i)
//             nums[i] = nums[i-1] + nums[i-2];
//         return nums[n];
//     }
// };
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄