Leetcode: Climbing Stairs



This question is asked a lot in Expedia and Amazon. Though it is labelled as an "easy" question, I thought it would be worth giving it a shot. Here it is:

You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb the top? 


Example 1:

Input: n = 2

Output: 2

Explanation: There are two ways to climb to the top.

1. 1 step + 1 step

2. 2 steps


Example 2:

Input: n = 3

Output: 3


Explanation: There are three ways to climb to the top.

1. 1 step + 1 step + 1 step

2. 1 step + 2 steps

3. 2 steps + 1 step

 

Constraints:

1 <= n <= 45


There are several solutions to this problem, first we want to go through the recursive solutions.

So, we want to recursively take the combination of the (i + 1)th and the (i + 2)th step, where i is the current step and n is the destination step. 

public class Solution {

    public int climbStairs(int n) {

        return climb_Stairs(0, n);

    }

    public int climb_Stairs(int i, int n) {

        if(i > n) return 0;

        if(i == n) return 1;

        return climb_Stairs(i + 1, n) + climb_Stairs(i + 2, n);

    }

}

This doesn't work because the time complexity is O(2^n) due to the depth of the recursion tree. 


public class Solution {

    public int climbStairs(int n) {

        if (n == 1) {

            return 1; 

        }

        int[] dp = new int[n + 1];

        //just one step

        dp[1] = 1;

        //just 2 1-step or 1 2-step

        dp[2] = 2;

        for(int i = 3; i <= n; i++) {

            //dynamic programming combination

            dp[i] = dp[i - 1] + dp[i - 2];

        }

        return dp[n];

    }

}



Comments

Popular Posts