Dynamic Programming: Foundations and 1D DP

Turn recursion into DP with memoisation and tabulation, define states clearly, and solve the classic one-dimensional DP problems.

Intermediate · about 8 hours · difficulty 3/5

Learn first: Backtracking, Greedy Algorithms

DP is recursion plus remembering answers to repeated subproblems. Most students fear it because they try to jump straight to a table. Go step by step instead.

The four-step method

  1. Write the recursive solution that tries all choices.
  2. Identify the state: the parameters that change (usually an index, maybe a remaining capacity).
  3. Add memoisation (top-down): cache results by state.
  4. Convert to tabulation (bottom-up), then optimise space if each row depends only on the previous one or two.

Classic 1D problems

  • Climbing Stairs and Fibonacci: dp[i] = dp[i - 1] + dp[i - 2].
  • Frog Jump (with k jumps): minimum cost to reach the end.
  • House Robber and House Robber II (circular: solve twice, excluding the first or the last house).
  • Decode Ways, Word Break, Coin Change (minimum coins), Coin Change II (number of ways), Perfect Squares.
  • Maximum Product Subarray (track both max and min).

Defining state well

Say the state in words: "dp[i] = the maximum money robbing houses 0..i". If you cannot say it, the recurrence will be wrong.

Pitfalls

  • Using 0 as "not computed" in a memo when 0 is a valid answer. Initialise with -1.
  • Coin Change II loop order: looping coins outside counts combinations; looping amount outside counts permutations.
  • Forgetting the base cases for negative indices.

You are ready to move on when you can take House Robber through all four steps (recursion, memo, table, O(1) space) without help.

Key concepts

  • Overlapping subproblems
  • Memoisation (top-down)
  • Tabulation (bottom-up)
  • Space optimisation
  • Defining the state
  • Counting vs optimisation DP

Mini project

Solve these 10 in 7 days, writing recursion, memo and table for each; log time and pattern: Climbing Stairs, Frog Jump (GfG), Min Cost Climbing Stairs, House Robber, House Robber II, Decode Ways, Coin Change, Coin Change II, Word Break, Maximum Product Subarray.

Check yourself

In Coin Change II, why does swapping the order of the coin loop and the amount loop change the answer?

Free resources