Sub topic 3
One-dimensional problems: coin change
This chapter assumes you can write a recurrence, fill a table in a valid order, and count states times work per state. It applies those skills to three classic problems.
One-dimensional problems: coin change
The state dp[a] is the fewest coins that sum to amount a. The recurrence is dp[a] = min(dp[a - c] + 1) over every coin c <= a, with base case dp[0] = 0. Each entry depends only on smaller amounts, so the table fills left to right.
def min_coins(coins, amount):
INF = float('inf')
dp = [0] + [INF] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a and dp[a - c] + 1 < dp[a]:
dp[a] = dp[a - c] + 1
return dp[amount] if dp[amount] != INF else -1
print(min_coins([1, 2, 5], 11)) # 3There are amount + 1 states and len(coins) work per state, so the cost is O(amount × len(coins)) time and O(amount) space. A common mistake is returning INF when no combination of coins reaches the amount. Check for it and return -1 instead.
Two-dimensional problems: longest common subsequence
The state dp[i][j] is the LCS length of the prefixes a[:i] and b[:j]. When the last characters match, dp[i][j] = dp[i-1][j-1] + 1. Otherwise it is max(dp[i-1][j], dp[i][j-1]). Row 0 and column 0 are 0.
Tracing back to recover the solution
The table holds lengths, not the subsequence itself. To recover one subsequence, start at dp[m][n] and walk backward through the table. On a match, record the character and move diagonally. Otherwise, move toward the larger neighbour.
def lcs(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
out = []
i, j = m, n
while i > 0 and j > 0:
if a[i - 1] == b[j - 1]:
out.append(a[i - 1])
i -= 1
j -= 1
elif dp[i - 1][j] >= dp[i][j - 1]:
i -= 1
else:
j -= 1
return ''.join(reversed(out))
print(lcs("ABCDE", "ACE")) # ACEShrinking the table: rolling arrays and variables
Each LCS row reads only the row above it, so two rows are enough to get the length. That cuts space to O(n). The catch is that the traceback needs the full table, so you have to decide which one you need: the value only, or the actual solution.
Putting it together: 0/1 knapsack
The state dp[c] is the best value that fits within capacity c. The code processes one item at a time and updates a single row in place.
def knapsack(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([1, 3, 4, 5], [1, 4, 5, 7], 7)) # 9The cost is O(items × capacity) time and O(capacity) space.
Exercise
In knapsack, what goes wrong if the capacity loop runs upward from w to capacity?
Show answer
dp[c - w] may already include the current item from the same pass, so an item can be taken more than once. That solves unbounded knapsack instead of 0/1 knapsack.