Climbing Stairs

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 to 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

My Solution

This is a dynamic programming problem. We can use memoization. We need a cache to store the output of the overlapping subproblems and at each iteration climbStairs(n) = climbStairs(n-1) + climbStairs(n-2), referring to the fact that we can climb either 1 or 2 stairs at a time. If we already computed for n, we just return the cached result.

Time complexity is O(n) because there are at most n subproblems. Space complexity is also O(n) to cache the subproblems.

class Solution {
    public int climbStairs(int n) {
        int[] cache = new int[n+1];

        return dp(n, cache);
    }

    public int dp(int n, int[] cache) {
        if (n == 1) {
            return 1;
        }

        if (n == 2) {
            return 2;
        }

        if (cache[n] != 0) {
            return cache[n];
        }

        int out = dp(n-2, cache) + dp(n-1, cache);
        cache[n] = out;
        return out;
    }
}
Previous
Previous

Remove Duplicates from Sorted List

Next
Next

Sqrt(x)