Dynamic Programming Basics
When does DP apply?
- Overlapping subproblems: the same smaller problem is solved again and again
- Optimal substructure: the best answer is built from best answers to smaller problems
Two styles
| Top-down (memoization) | Bottom-up (tabulation) |
|---|---|
| Recursion + cache of results | Fill a table from the smallest cases up |
| Easy to write from a recursive idea | No recursion depth limit, often faster |
| Computes only needed states | Computes all states |
The DP recipe ✅
- Define the state: what does
dp[i](ordp[i][j]) mean? - Recurrence: how is it built from smaller states?
- Base cases
- Order of computation (bottom-up) or memoize (top-down)
- Answer: which cell holds it?
Classic problems
| Problem | State | Recurrence |
|---|---|---|
| Fibonacci / climbing stairs | ways to reach step i | dp[i] = dp[i-1] + dp[i-2] |
| Coin change (min coins) | min coins for amount a | dp[a] = min(dp[a - c] + 1) |
| 0/1 Knapsack (budget!) | best value with budget b using first i items | take or skip each item |
| Longest common subsequence | LCS of prefixes i, j | match → +1, else max of skipping one |
| Edit distance | edits to turn prefix i into prefix j | insert/delete/replace |
| Max subarray (Kadane) | best sum ending at i | max(a[i], dp[i-1] + a[i]) |
Space optimization
If dp[i] only needs the previous row/values, keep just those → O(n) or O(1) memory.
Reconstructing the solution
Store choices (or walk back through the table) to know which coins/items were chosen, not just the best value.
Example
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
long long ways_to_climb(int n) { // 1 or 2 steps at a time
long long prev2 = 1, prev1 = 1; // O(1) space
for (int i = 2; i <= n; ++i) { long long cur = prev1 + prev2; prev2 = prev1; prev1 = cur; }
return prev1;
}
std::vector<int> min_coins(const std::vector<int>& coins, int amount) {
const int INF = 1'000'000;
std::vector<int> dp(amount + 1, INF), last(amount + 1, -1);
dp[0] = 0;
for (int a = 1; a <= amount; ++a)
for (int c : coins)
if (c <= a && dp[a - c] + 1 < dp[a]) { dp[a] = dp[a - c] + 1; last[a] = c; }
if (dp[amount] >= INF) return {};
std::vector<int> used;
for (int a = amount; a > 0; a -= last[a]) used.push_back(last[a]); // reconstruct
return used;
}
struct Item { std::string name; int cost; int value; };
std::pair<int, std::vector<std::string>> knapsack(const std::vector<Item>& items, int budget) {
int n = static_cast<int>(items.size());
std::vector<std::vector<int>> dp(n + 1, std::vector<int>(budget + 1, 0));
for (int i = 1; i <= n; ++i)
for (int b = 0; b <= budget; ++b) {
dp[i][b] = dp[i - 1][b]; // skip item i
if (items[i - 1].cost <= b)
dp[i][b] = std::max(dp[i][b], dp[i - 1][b - items[i - 1].cost] + items[i - 1].value); // take it
}
std::vector<std::string> chosen;
for (int i = n, b = budget; i > 0; --i)
if (dp[i][b] != dp[i - 1][b]) { chosen.push_back(items[i - 1].name); b -= items[i - 1].cost; }
return { dp[n][budget], chosen };
}
int edit_distance(const std::string& a, const std::string& b) {
std::vector<std::vector<int>> dp(a.size() + 1, std::vector<int>(b.size() + 1));
for (std::size_t i = 0; i <= a.size(); ++i) dp[i][0] = static_cast<int>(i);
for (std::size_t j = 0; j <= b.size(); ++j) dp[0][j] = static_cast<int>(j);
for (std::size_t i = 1; i <= a.size(); ++i)
for (std::size_t j = 1; j <= b.size(); ++j)
dp[i][j] = (a[i - 1] == b[j - 1]) ? dp[i - 1][j - 1]
: 1 + std::min({ dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1] });
return dp[a.size()][b.size()];
}
int main() {
std::cout << "ways to climb 10 steps: " << ways_to_climb(10) << ", 50 steps: " << ways_to_climb(50) << '\n';
auto coins = min_coins({ 1, 5, 10, 25, 50 }, 87);
std::cout << "fewest coins for 87: " << coins.size() << " ->";
for (int c : coins) std::cout << ' ' << c;
std::cout << "\ngreedy fails for coins {1, 3, 4} and 6; DP uses " << min_coins({ 1, 3, 4 }, 6).size() << " coins\n";
std::vector<Item> wishlist = { { "headphones", 3000, 60 }, { "course", 4000, 90 },
{ "shoes", 2500, 40 }, { "books", 1500, 50 } };
auto [value, picks] = knapsack(wishlist, 7000);
std::cout << "best happiness within Rs. 7000: " << value << " ->";
for (const auto& p : picks) std::cout << ' ' << p;
std::cout << '\n';
std::cout << "edit distance kitten -> sitting: " << edit_distance("kitten", "sitting")
<< ", budgt -> budget: " << edit_distance("budgt", "budget") << '\n';
return 0;
}
/* Output:
ways to climb 10 steps: 89, 50 steps: 20365011074
fewest coins for 87: 5 -> 1 1 10 25 50
greedy fails for coins {1, 3, 4} and 6; DP uses 2 coins
best happiness within Rs. 7000: 150 -> course headphones
edit distance kitten -> sitting: 3, budgt -> budget: 1
*/