70. 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步+1步或者n-2步+2步,所以 f[n] = f[n-1] + f[n-2]

class Solution {
public:
    int climbStairs(int n) {
        vector<int> dp(n + 1, 0);
        dp[1] = 1;
        dp[2] = 2;
        for(int i = 3; i <= n; i++){
            dp[i] = dp[i - 1] +  dp[i - 2];
        }
        return dp[n];
    }
};

另一种写法

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

你可能感兴趣的:(70. Climbing Stairs)