O(n) time and O(1) space using C++


  • 0
    A
        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;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.