Data Structures & Algorithms · Module 11 · Lesson 11 min read

DP Basics

When to use DP

A problem fits DP when it has:

  1. Overlapping subproblems: the same smaller question is asked many times.
  2. Optimal substructure: the best answer is built from the best answers to smaller parts.

Typical wording: "number of ways", "minimum or maximum cost", "longest", "can you reach…".

Two styles

Top-down (memoisation)Bottom-up (tabulation)
recursion + a cache (@lru_cache)fill a table from small to large
easy to write from the recurrenceno recursion limit, often faster
only computes the states it needscomputes every state

The 4-step recipe

  1. State: what does dp[i] mean? ("ways to reach step i")
  2. Transition: how does dp[i] use smaller states? (dp[i] = dp[i-1] + dp[i-2])
  3. Base cases: dp[0], dp[1].
  4. Answer: which state holds the result? (dp[n])

Example: climbing stairs

You can climb 1 or 2 steps at a time. Ways to reach step n = ways(n − 1) + ways(n − 2). Fibonacci again!

Space optimisation

If dp[i] only needs the last one or two values, keep just those variables: O(1) space instead of O(n).

💡 Write the plain recursive solution first, add a cache, then convert to a table if needed.

Example

Python
from functools import lru_cache

# Top-down: memoised recursion
@lru_cache(maxsize=None)
def climb(n):
    if n <= 2:
        return n
    return climb(n - 1) + climb(n - 2)

# Bottom-up: table
def climb_table(n):
    if n <= 2:
        return n
    dp = [0] * (n + 1)
    dp[1], dp[2] = 1, 2
    for i in range(3, n + 1):
        dp[i] = dp[i - 1] + dp[i - 2]
    return dp[n]

# Space-optimised: O(1)
def max_robbery(houses):
    """Max money robbing houses with no two neighbours robbed."""
    take, skip = 0, 0
    for money in houses:
        take, skip = skip + money, max(take, skip)
    return max(take, skip)

print(climb(10), climb_table(10))          # 89 89
print(climb(50))                           # 20365011074 — instant
print(max_robbery([2, 7, 9, 3, 1]))        # 12  (2 + 9 + 1)