curriculum/challenges/english/blocks/review-dynamic-programming/67f39e2119042d2f2ca926ff.md
def climb_stairs_memo(n, memo={}):
"""Dynamic programming with memoization"""
# Check if we've already calculated this value
if n in memo:
return memo[n] # Return cached result - O(1) lookup!
# Base cases
if n <= 2:
return n
# Calculate once and store in memo for future use
memo[n] = climb_stairs_memo(n-1, memo) + climb_stairs_memo(n-2, memo)
return memo[n]
def climb_stairs_tabulation(n):
"""Dynamic programming with tabulation"""
if n <= 2:
return n
# Create array to store results for all steps from 0 to n
dp = [0] * (n + 1)
dp[1] = 1 # 1 way to reach step 1
dp[2] = 2 # 2 ways to reach step 2
# Build up the solution iteratively
for i in range(3, n + 1):
# 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.