My java solution with O(1) memory + O(n) time


  • 0
    T
    public int climbStairs(int n) {
        if(n==0) return 0;
        if(n==1) return 1;
        if(n==2) return 2;
        
        int i=3;
        int this_step=0;
        int one_step_shorter=2;
        int two_step_shorter=1;
        
        while(i<=n){
            this_step=one_step_shorter+two_step_shorter;
            two_step_shorter=one_step_shorter;
            one_step_shorter=this_step;
            i++;
        }
        
        return this_step;
    }

Log in to reply
 

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