AlgoMaster Logo

Climbing Stairs

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Solution

The climbing stairs problem can be solved using a recursive approach. The core idea is to think of climbing stairs as making a series of steps. At each step, you have two choices: take one step or take two steps.

Intuition:

  • Start from the base step (step 0) and determine how many ways can you reach the top step (step n).
  • At each step i, you have two choices: move to i+1 or i+2.
  • Recursively calculate the number of ways to reach the top from each of these steps.
  • The base cases are:
    • If you reach step n, there's 1 way to stay there (do nothing).
    • If you surpass step n, there are 0 ways.

Code:

2. Dynamic Programming (Top-Down Memoization)

This approach uses memoization to store results of subproblems, reducing repeated calculations.

Intuition:

  • Similar to the recursive approach, but use an array to store already computed results for each step.
  • The memoization array memo stores results of the number of ways to climb to the top from each step.
  • Fill in the memoization table on the fly, storing each result for quick access.

Code:

3. Dynamic Programming (Bottom-Up)

This approach involves using an iterative dynamic programming approach, filling from the bottom up without recursion.

Intuition:

  • Initialize a DP array dp[] where dp[i] represents the number of ways to reach step i.
  • Start with base conditions dp[0] = 1 and dp[1] = 1.
  • Iteratively fill the array using the relation dp[i] = dp[i-1] + dp[i-2].

Code:

4. Optimized Dynamic Programming (Space-Optimization)

By observing that the DP approach only uses the last two numbers, we can optimize space usage.

Intuition:

  • Instead of maintaining the whole DP array, keep only two variables to hold the last two states.
  • This reduces space complexity substantially.

Code: