Dynamic programming
Dynamic programming solves a problem by combining answers to overlapping subproblems, storing each subproblem's result once. Recursion without a table repeats work and often becomes exponential; a table makes it polynomial.
Detailed Explanation
Fibonacci is the mascot. fib(n) = fib(n-1) + fib(n-2) recomputes fib(n-2) from both branches. A vector<long long> dp(n+1) with dp[0]=0, dp[1]=1, dp[i]=dp[i-1]+dp[i-2] is O(n) time and O(n) space. Two variables are O(1) space. That is DP: identify the subproblem (fib(k)), the recurrence, the base cases, and the evaluation order.
Two styles.
Memoisation (top-down). Recurse, and the first time you compute f(args) store it in a map or array. Later calls return the store. Natural when the recurrence is easy to write and not every state is needed.
Tabulation (bottom-up). Allocate the table, fill base cases, then iterate in an order that only reads already-filled cells. Faster constants, no recursion depth, easier to shrink to rolling arrays.
A DP solution has a state (the arguments that identify a subproblem), a transition (how to compute it from smaller states), and an answer location (dp[n], max(dp[n][j]), …). Write those three sentences before you write code.
Classic C++ shapes:
- 1D: coins, climbing stairs, house robber —
vector<long long>. - 2D: LCS, knapsack, edit distance —
vector<vector<int>>or a flattenedvector<int>(rows * cols). - Interval: matrix chain, palindrome partition —
dp[l][r]. - Bitmask: TSP on ≤ 20 cities —
dp[mask][v]. - Digit DP and tree DP: state includes position or a node.
Use long long for counts that can grow. Initialise the table to a sentinel (-1 for "unknown" in memoisation, INF for "impossible" in shortest-path DP). Overflow and sentinel collisions (-1 as a legal answer) are the usual bugs.
DP versus greedy: if a local choice can block a better global answer, you need DP or search. DP versus divide-and-conquer: DP is for overlapping subproblems; merge sort's halves do not overlap.
Space optimisation: if dp[i] depends only on dp[i-1], keep two rows. Interviewers love this; production code should stay 2D until a profiler says otherwise.
Code Examples
#include <cstddef>
#include <iostream>
#include <vector>
long long fib(int n) {
if (n <= 1) return n;
std::vector<long long> dp(static_cast<std::size_t>(n) + 1);
dp[1] = 1;
for (int i = 2; i <= n; ++i) {
dp[static_cast<std::size_t>(i)] =
dp[static_cast<std::size_t>(i - 1)] + dp[static_cast<std::size_t>(i - 2)];
}
return dp[static_cast<std::size_t>(n)];
}
int main() {
std::cout << fib(10) << '\n'; // prints: 55
}#include <algorithm>
#include <string>
#include <vector>
int lcs(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) {
for (std::size_t j = 0; j < b.size(); ++j) {
if (a[i] == b[j]) dp[i + 1][j + 1] = dp[i][j] + 1;
else dp[i + 1][j + 1] = std::max(dp[i][j + 1], dp[i + 1][j]);
}
}
return dp[a.size()][b.size()];
}
int main() {
return lcs("abc", "ac") == 2 ? 0 : 1;
}Common Gotchas
Recursing without a memo on overlapping states
`fib` without a table is O(φⁿ). If the call tree is a DAG, store results.
Evaluation order
bottom-up `dp[i]` that reads `dp[i+1]` is uninitialised. Draw the dependency arrows.
Sentinel versus legal value
if `-1` is a valid answer, use `optional` or a separate `seen` table.
`vector<vector<int>>` of n×n has n allocations
flatten to one vector if the inner loop is hot.