Climbing Stairs in TypeScript

function climbStairs(n: number): number {
  // Create an array to store the distinct ways to climb for each number of steps
  const dp: number[] = new Array(n + 1);

  // Base cases:
  // There is only one way to climb 0 steps (do nothing)
  dp[0] = 1;
  // There is only one way to climb 1 step (take one step)
  dp[1] = 1;

  // Iterate from 2 to n
  for (let i = 2; i <= n; i++) {
    // The number of distinct ways to climb i steps is the sum of:
    // 1. The number of distinct ways to climb (i - 1) steps (taking one step from the previous step)
    // 2. The number of distinct ways to climb (i - 2) steps (taking two steps from two steps before)
    dp[i] = dp[i - 1] + dp[i - 2];
  }

  // Return the number of distinct ways to climb n steps
  return dp[n];
}

PrevNext