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?

class Solution {
public:
    int climbStairs(int n) {
        if (n <= 1) return 1;
        vector<int> dp(n);
        dp[0] = 1; //0 代表第一层 因为i=n就退出forloop了
        dp[1] = 2; // 上第二层有两种方式 第一种是1次2step,第二种是2次1step
        for (int i = 2; i < n; ++i) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp.back();
    }
};
int climbStairs(int n) {
    int a = 1, b = 1;
    while (n--)
        a = (b += a) - a;
    return a;
}
class Solution {
public:
    int climbStairs(int n) {
        int a=1;
        int b=2;
        if(n==1) return a;
        if (n==2) return b;
         while(--n){
            b+=a;
            a=b-a;
        }
        return a;


    }
};

Variable a tells you the number of ways to reach the current step, and b tells you the number of ways to reach the next step. So for the situation one step further up, the old b becomes the new a, and the new b is the old a+b, since that new step can be reached by climbing 1 step from what b represented or 2 steps from what a represented.

REF:

results matching ""

    No results matching ""