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?

题目解析:

这道题说白了是递归,更好点是动态规划,要求n,从n-1和n-2来。a[i] = a[i-1] + a[i-2]。本来想设一个数组,但由于只涉及到两个数之间的求和,并且是相邻的两个数,就没必要去设数组了,只用两个变量即可。

class Solution {
public:
    int climbStairs(int n) {
        if(n == 1 || n== 2)
            return n;
        int temp1 = 1;
        int temp2 = 2;
        for(int i = 3;i <= n;i++){
            int temp = temp1+temp2;
            temp1 = temp2;
            temp2 = temp;
        }
        return temp2;
    }
};




点赞