Files
hello-algo/en/codes/javascript/chapter_dynamic_programming/climbing_stairs_backtrack.js
T
Yudong Jin 14c314c08c Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
2026-10-31 03:35:51 +08:00

35 lines
1.0 KiB
JavaScript

/**
* File: climbing_stairs_backtrack.js
* Created Time: 2023-07-26
* Author: yuan0221 ([email protected])
*/
/* Backtracking */
function backtrack(choices, state, n, res) {
// When step n is reached, increase the number of ways by 1
if (state === n) res.set(0, res.get(0) + 1);
// Iterate over all choices
for (const choice of choices) {
// Prune: do not go beyond step n
if (state + choice > n) continue;
// Try: make a choice and update the state
backtrack(choices, state + choice, n, res);
// Backtrack
}
}
/* Climbing stairs: backtracking */
function climbingStairsBacktrack(n) {
const choices = [1, 2]; // Choose to climb 1 or 2 steps
const state = 0; // Start climbing from step 0
const res = new Map();
res.set(0, 0); // Store the number of ways at key 0 in res
backtrack(choices, state, n, res);
return res.get(0);
}
/* Driver code */
const n = 9;
const res = climbingStairsBacktrack(n);
console.log(`Number of ways to climb ${n} stairs: ${res}`);