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.
Building upon understanding of Climbing stairs (Memoization). Tabulation essentially reconstructs the cache.
Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.
The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.
def climb(n): if n < 1: return 0 if n == 1: return 1 if n == 2: return 2 result = 0 prev_1 = 2 prev_2 = 1 for i in range(3, n + 1): result = prev_1 + prev_2 prev_2 = prev_1 prev_1 = result return result n = 5 print(climb(n))
function climb(n) { if (n < 1) { return 0; } if (n == 1) { return 1; } if (n === 2) { return 2; } let result = 0; let prev_1 = 2; let prev_2 = 1; for (let i = 3; i <= n; i++) { result = prev_1 + prev_2; prev_2 = prev_1; prev_1 = result; } return result; } const n = 5; console.log(climb(n));