Part 16 / Topic 12 of 12
Dynamic programming
Dynamic programming (DP) solves a problem by breaking it into overlapping sub-problems, solving each sub-problem exactly once, and reusing the answer — the fibonacci memoization in section 5 was already DP, one topic early, because that's genuinely the simplest possible example of it. There are two ways to apply the idea:
| Approach | Direction | Mechanism | Looks like |
|---|---|---|---|
| Memoization (top-down) | start from the big problem | recursion + a cache | fibonacciMemoized |
| Tabulation (bottom-up) | start from the smallest sub-problems | fill a table in order, no recursion | minCoinsTabulation |
// Bottom-up / tabulation: minimum coins to make an amount, filled left to right.
static int minCoinsTabulation(int[] coins, int amount) {
int[] table = new int[amount + 1];
Arrays.fill(table, Integer.MAX_VALUE);
table[0] = 0;
for (int sub = 1; sub <= amount; sub++) {
for (int coin : coins) {
if (coin <= sub && table[sub - coin] != Integer.MAX_VALUE) {
table[sub] = Math.min(table[sub], table[sub - coin] + 1);
}
}
}
return table[amount] == Integer.MAX_VALUE ? -1 : table[amount];
}
$ javac DynamicProgrammingDemo.java
$ java DynamicProgrammingDemo
-- minimum coins to make Rs 23, coins [1, 2, 5, 10] --
memoization (top-down): 4 coins
tabulation (bottom-up): 4 coins
same answer: true
-- 0/1 knapsack: best value of parcels under a weight limit --
items: [books, laptop, shoes, groceries]
values: [200, 1800, 600, 350], weights: [2, 3, 1, 4], limit: 5 kg
best possible value: Rs 2400 (laptop + shoes = 1800 + 600, 4 kg)
-- longest common subsequence: fuzzy-matching product titles --
"WIRELESS BLUETOOTH HEADPHONES"
"BLUETOOTH WIRELESS HEADSET"
longest common subsequence length: 15 characters
The 0/1 knapsack example has the exact same shape as the backtracking "fitting combinations" example in section 5 — for each item, either leave it out or take it — but DP fills a table of "best value achievable with the first i items and capacity cap" directly, in O(items × capacity), instead of generating every subset and filtering the ones that fit. That's the real difference backtracking vs. DP comes down to: backtracking explores every valid combination (useful when you need to list them, as section 5 did); DP computes just the best answer, reusing overlapping sub-problems instead of regenerating them.
🔍 Going deeper: not every backtracking problem has overlapping sub-problems (the "all pickup orders" permutation example in section 5 does not — every prefix of a permutation is genuinely distinct), and DP does not apply to those. DP is for problems with both optimal substructure (the best answer is built from the best answers to sub-problems) and overlapping sub-problems (the same sub-problem gets asked for more than once).
Full program: examples/dynamic-programming/DynamicProgrammingDemo.java.
Done here? The practice set for Part 16 — including the solutions — is on the part page.