Computer >> Computer tutorials >  >> Programming >> Javascript

How to implement backtracking for a climbing stairs practice in JavaScript?


Suppose we need to climb a staircase that has n steps, and we decide to get some extra exercise by jumping up the steps.

We can cover at most k steps in a single jump. k will be either 1 or 2 irrespective of the number of steps in the staircase.

We are required to return all the possible sequences of jumps that you could take to climb the staircase, sorted.

For example −

for n = 4 and k = 2,

the output should be −

climbingStaircase(n, k) = [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2]];

Example

The code for this will be −

const n = 4;
const climbStairs = (n) => {
   if (n == 0) return 0;
   let memory = new Map();
   let recur = (left) => {
      if (memory.has(left)) return memory.get(left);
      if (left <= 0) return 0;
      if (left == 1) return 1;
      if (left == 2) return 2;
      memory.set(left, recur(left − 2) + recur(left − 1));
      return memory.get(left);
   };
   return recur(n);
};
console.log(climbStairs(n));

Output

And the output in the console will be −

5