Dynamic programming
Dynamic programming solves a problem by combining answers to overlapping smaller problems. You store each sub-answer so you compute it once. Recursion plus a table, or a bottom-up loop, are the two styles.
Detailed Explanation
Greedy picks a local winner and hopes. DP considers every relevant smaller state. The reason it is not brute force is overlapping: Fibonacci without storage recomputes f(3) many times; with an array it computes each n once.
Two ingredients must be present. Optimal substructure: an optimal answer is built from optimal answers to smaller instances. Overlapping subproblems: the same smaller instance appears more than once. Shortest paths in a DAG, knapsack, edit distance, and "number of ways" all fit.
A state is the tuple that identifies a subproblem: (index, remainingCapacity), (i, j) in two strings, (node, visitedMask) in TSP-like tours. The transition writes how a state depends on others. Time is (number of states) × (work per state). Memory is the table, sometimes reducible to the last row.
Top-down is recursion with a memo array or map, often Integer[] with null meaning unknown. Bottom-up fills the table in an order that respects dependencies (increasing length, increasing index). Top-down only computes reachable states. Bottom-up is easier to reason about for iteration limits and is often faster in Java (no call stack).
You reach for DP when a recursive search repeats work and the state space is small enough (typically up to about 10^6 to 10^7 simple states). You reach for greedy when an exchange argument says the local pick is safe. You reach for BFS when the "cost" is unweighted hops.
The cost of a wrong state is a wrong answer that looks structured. The cost of an int table for counts is overflow; use long or modulo. The cost of a recursive DP on a wide graph is stack overflow. Initialize base cases explicitly. For "minimum", start cells at a sentinel larger than any real answer, not 0.
Code Examples
public class Fib {
static long fib(int n) {
if (n < 2) {
return n;
}
long[] dp = new long[n + 1];
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
public static void main(String[] args) {
System.out.println(fib(10)); // prints: 55
}
}public class Knapsack {
static int best(int[] weight, int[] value, int cap) {
int[] dp = new int[cap + 1];
for (int i = 0; i < weight.length; i++) {
for (int c = cap; c >= weight[i]; c--) { // backward: 0/1, not unbounded
dp[c] = Math.max(dp[c], dp[c - weight[i]] + value[i]);
}
}
return dp[cap];
}
public static void main(String[] args) {
System.out.println(best(new int[] {2, 3, 4}, new int[] {3, 4, 5}, 5)); // prints: 7
}
}Common Gotchas
Forward 1D update turns 0/1 knapsack into unbounded knapsack
iterate capacity downward for 0/1.
`int` overflows on "number of ways"
use `long` or the required modulo.
Memo `int[]` initialized to 0 cannot store a real answer of 0
use `Integer`, a sentinel, or a `boolean[] seen`.
Recursive DP can overflow the stack
prefer bottom-up for large index ranges.