Climbing stairs (Memoization)

There are n stairs, and a person standing at the bottom can climb either 1 stair or 2 stairs at a time, count the number of ways that a person can reach at the top.

Hint

This algorithm uses memoization to improve performance. It's same as the recursive version of Climbing stairs, but with a special 'cache' to store results. The 'cache key' is crucial. It's how we identify and store past results. Sometimes we need one key, sometimes multiple keys. We add code to:

# Python implementation
cache = {}

def climb(n):
  if n < 1:
    return 0

  if n == 1:
    return 1

  if n == 2:
    return 2

  if n not in cache:
    cache[n] = climb(n - 1) + climb(n - 2)
  
  return cache[n]

n = 5

print(climb(n))
// Javascript implementation
const cache = {}

function climb(n) {
  if (n < 1) {
    return 0;
  }

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

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

  if (cache[n] === undefined) {
    cache[n] = climb(n - 1) + climb(n - 2);
  } 
  
  return cache[n];
}

const n = 5;

console.log(climb(n));