This approach uses recursion to explore the different ways to reach the top. To optimize, we use memoization to store results of subproblems to avoid redundant calculations. This ensures that each subproblem is solved only once, dramatically improving efficiency.
Time Complexity: O(n), as each state is only computed once.
Space Complexity: O(n), due to the memoization array.
1function climbStairs(n) {
2 const memo = {};
3 function climb(n) {
4 if (n <= 2) return n;
5 if (n in memo) return memo[n];
6 return memo[n] = climb(n - 1) + climb(n - 2);
7 }
8 return climb(n);
9}
10
11console.log(climbStairs(3));
This JavaScript solution leverages a helper function to recursively calculate stairs traversed, optimizing through memoization. The memo
object stores previous results to avoid extra calculations.
This approach builds from the base up using a table to store results at each step. Starting with known base cases, each subsequent result is built by combining previous results. This eliminates the recursive overhead, making it a very efficient algorithm.
Time Complexity: O(n), since each value is calculated sequentially in a loop.
Space Complexity: O(n), for storing the results in the dp
array.
1using System;
2
3public class Solution {
4 public int ClimbStairs(int n) {
5 if (n <= 2) return n;
6 int[] dp = new int[n + 1];
7 dp[1] = 1;
8 dp[2] = 2;
9 for (int i = 3; i <= n; i++)
10 {
11 dp[i] = dp[i - 1] + dp[i - 2];
12 }
13 return dp[n];
14 }
15
16 public static void Main(string[] args) {
17 Solution sol = new Solution();
18 Console.WriteLine(sol.ClimbStairs(3));
19 }
20}
This C# solution uses a basic dynamic programming approach with an dp
array to iteratively calculate the number of ways to climb the stairs, starting from the base cases. The iterative loop constructs the final answer without recursive calls.