Dynamic programming
Dynamic programming solves a problem by combining answers to overlapping subproblems, storing each answer once. In Rust that store is usually a Vec, a HashMap, or an #[cached]-shaped memo table.
Detailed Explanation
A recursive solution that repeats the same subproblem is exponential. DP is that recursion plus a table. Fibonacci is the teaching example: fib(n) calls fib(n-1) and fib(n-2), which recompute everything below. A Vec of n entries fills each index once and is O(n).
Two styles. Top-down: write the recursive function and memoise with a &mut Vec<Option<T>> or a HashMap. Bottom-up: decide an order so that when you compute dp[i], the smaller states are already done, and write a loop. Bottom-up is usually faster (no call overhead, tight array) and easier to reason about space (you can keep only the last row). Top-down is easier when only a sparse subset of states is needed.
State design is the actual skill. The state must include everything that the future answer depends on: index in the array, remaining capacity, whether you have used the skip, the last colour. Too little state is a wrong answer. Too much state is an exponential table. In Rust, encode the state as indices into Vecs when the ranges are small and dense. Use a HashMap of tuples when they are sparse.
Integer overflow shows up in DP more than in other algorithms because you add many ways to count. Use u64, saturating ops, or a modulus, deliberately. Recursion-plus-memo on a deep DAG can still overflow the stack; bottom-up or an explicit stack avoids that.
When you reach for DP: overlapping subproblems plus optimal substructure (or counting). When you reach for greedy: you can prove a local choice is safe. When you reach for prefix sums: the "DP" is only range sums.
Code Examples
fn fib(n: usize) -> u64 {
if n < 2 {
return n as u64;
}
let mut dp = vec![0u64; n + 1];
dp[1] = 1;
for i in 2..=n {
dp[i] = dp[i - 1] + dp[i - 2];
}
dp[n]
}
fn main() {
println!("{}", fib(10)); // prints: 55
}Common Gotchas
Top-down memo still uses the call stack
A chain of n unique states is n frames. Fill a table bottom-up when n is large.
Count DPs overflow `i32` quickly
Pick `u64`, saturating arithmetic, or a stated modulus.
A `HashMap` memo is for sparse states
A dense `0..n` should be a `Vec`. Hashing a million sequential keys is wasted work.
Forgetting a dimension of state
If the answer depends on "have I used the coupon", that boolean is part of the index. Missing it reuses a wrong subanswer.