LeetCode70: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?

设到第i台阶有A[i]

那么到第1台阶有A[1]=1种方法

那么到第2台阶有A[2]=2种方法

那么到第3台阶有A[3]=A[1]+A[2]=3种方法

那么到第4台阶有A[4]=A[2]+A[3]=5种方法

...

那么这个动态规划的初始状态A[i]就代表到第i台阶的方法。状态转移方程:

A[i]=A[i-1]+A[i-2].i>=3

A[1]=1,A[2]=2

并且由于上面A[i]只与A[i-1]和A[i-2]有关,所以可以和前面的House Robber问题一样在O(1)的空间复杂度内解决问题。

class Solution {
public:
    int climbStairs(int n) {
        if(n==1)
            return 1;
        if(n==2)
            return 2;
            
        int last=2,pLast=1;
        for(int i=3;i<=n;i++)
        {
            pLast=last+pLast;
            swap(pLast,last);
        }
        return last;
    }
};



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