curriculum/challenges/english/blocks/review-dynamic-programming-js/6999b92ca334e9cf237dc92d.md
function climbStairsMemo(n, memo = {}) {
// If already calculated, return cached value
if (memo[n] !== undefined) {
return memo[n];
}
// Base cases: 1 way for 1 step, 2 ways for 2 steps
if (n <= 2) {
return n;
}
// Calculate once and store in memo for future use
memo[n] =
climbStairsMemo(n - 1, memo) +
climbStairsMemo(n - 2, memo);
return memo[n];
}
function climbStairsTabulation(n) {
if (n <= 2) {
return n;
}
// Create an array to store solutions from 0 to n
const dp = new Array(n + 1).fill(0);
// Base cases
dp[1] = 1; // 1 way to reach step 1
dp[2] = 2; // 2 ways to reach step 2
// Build up the solution iteratively
for (let i = 3; i <= n; i++) {
// Ways to reach step i = ways to reach (i-1) + ways to reach (i-2)
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
You should consider using dynamic programming in the following scenarios:
Review Dynamic Programming topics and concepts.