Sub topic 2
0/1 knapsack: recurrence, table, and space reduction
0/1 knapsack
Each item can be taken once or skipped. Let dp[i][c] be the best value using the first i items with capacity c. Then dp[i][c] = max(dp[i-1][c], dp[i-1][c-w_i] + v_i) when c >= w_i, and dp[0][c] = 0. Fill rows in increasing i. Keeping one row and iterating capacity downward reduces space from O(nW) to O(W).
def knapsack_01(weights, values, capacity):
dp = [0] * (capacity + 1)
for w, v in zip(weights, values):
for c in range(capacity, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
print(knapsack_01([1, 3, 4, 5], [1, 4, 5, 7], 7)) # 9Longest common subsequence
Let L[i][j] be the LCS length of the first i characters of a and the first j characters of b. If a[i-1] == b[j-1], then L[i][j] = L[i-1][j-1] + 1. Otherwise L[i][j] = max(L[i-1][j], L[i][j-1]). Time is O(mn).
Edit distance
Let D[i][j] be the minimum edits (insert, delete, replace) to turn the first i characters of one string into the first j of the other. Base cases are D[i][0] = i and D[0][j] = j. The recurrence takes the minimum of D[i-1][j] + 1, D[i][j-1] + 1, and D[i-1][j-1] + cost, where cost is 0 on a match and 1 otherwise.
Matrix chain multiplication
For matrices A_i..A_j, let M[i][j] be the fewest scalar multiplications. Then M[i][i] = 0 and M[i][j] = min over k of M[i][k] + M[k+1][j] + p[i-1]*p[k]*p[j], where p holds the matrix dimensions. Fill by increasing chain length. Time is O(n^3).
Coin change
For minimum coins, let C[v] = 1 + min(C[v-c]) over coins c <= v, with C[0] = 0. For counting ways, loop over coins in the outer loop and amounts in the inner loop, so each combination is counted once regardless of order.
Graph representations
An adjacency list stores each vertex's neighbours, using O(V + E) space and O(degree) time to check an edge. An adjacency matrix uses O(V^2) space and O(1) time to check an edge. Lists suit sparse graphs, and matrices suit dense ones.
BFS and DFS
BFS uses a queue and visits vertices by distance, in O(V + E) time. DFS uses a stack or recursion and goes deep first, also in O(V + E). In a directed DFS, an edge leads to a tree, back, forward, or cross edge. A back edge reveals a cycle.
Topological sort of a DAG
A topological order lists vertices so every edge points forward. Reverse the DFS finish order, or repeatedly remove vertices with in-degree 0 (Kahn's algorithm). Both run in O(V + E) and apply only to directed acyclic graphs.
Exercise
Using the knapsack table idea, what is the 0/1 knapsack answer for weights [2, 3] and values [3, 4] with capacity 4?
Show answer
4. Taking only the item of weight 3 gives value 4, which beats taking the weight-2 item alone (value 3). Both items together weigh 5, which exceeds the capacity.