Recurrences and Dynamic Programming

Computer Science & Algorithms · Advanced Placement

Overlapping subproblems

{{illustration:cd-fib}}

- Naive recursion repeats the same subproblems. - Memoization stores each answer once.

Designing a recurrence

{{illustration:cd-dpflow}}

| Problem | Recurrence | Table size | |---|---|---| | Fibonacci | F(n) = F(n − 1) + F(n − 2) | n + 1 | | LCS | match: 1 + diag; else max(up, left) | (m + 1)(n + 1) | | 0/1 knapsack | max(skip, take) | n × W | | coin change | 1 + min over coins | amount + 1 |

Table sizes

{{illustration:cd-tables}}

- Time is cells times work per cell. - Space can often be reduced to one or two rows.

Pseudo-polynomial time

{{illustration:cd-knap}}

- Knapsack runs in Θ(nW), polynomial in the numeric value of W only. - The problem is NP-hard in the bit length of W.