O(1) space O(n) time simple java solution 0ms


  • 2
    H
     public int climbStairs(int n) {
            int step = 1;
            int prestep = 1;
            int temp = 0;
            while(--n>0){
                temp = step;
                step = step+prestep;
                prestep =temp;
            }
            return step;
        }
    

    before this I tend to use recursion like below.
    bit it will cost 3000ms too bad..

    public static int climbStairs(int n) {
    		return n > 1 ? (climbStairs(n - 1) + climbStairs(n - 2)) : 1;
    	}

Log in to reply
 

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