Docsity

CS 161 — Dynamic Programming, Exams of Nursing

Toggle sidebar
bg1
CS 161 — Dynamic Programming
Table of Contents
1. What Is Dynamic Programming?
2. The DP Recipe
3. Memoization versus Tabulation
4. Fibonacci
5. Bellman-Ford
6. Floyd-Warshall
7. Longest Common Subsequence
8. Knapsack Problems
9. Maximum-Weight Independent Set in Trees
10. DP versus Greedy Algorithms
11. Common Mistakes
12. Official CS 161 References
What Is Dynamic Programming?
Dynamic programming solves a large problem by:
1. Breaking it into smaller subproblems.
2. Solving each subproblem once.
3. Storing its solution in a table or cache.
4. Combining stored solutions to solve larger subproblems.
Stanford describes DP as a meta-technique, not a single algorithm: it is a general method for
designing algorithms when a problem has suitable recursive structure.stanford-cs161.github+1
Two required properties
A problem is suitable for DP when it has:
Property
Meaning
Optimal substructure
An optimal solution contains optimal solutions to subproblems
Overlapping subproblems
The same subproblems recur many times
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download CS 161 — Dynamic Programming and more Exams Nursing in PDF only on Docsity!

CS 161 — Dynamic Programming

Table of Contents

  1. What Is Dynamic Programming?
  2. The DP Recipe
  3. Memoization versus Tabulation
  4. Fibonacci
  5. Bellman-Ford
  6. Floyd-Warshall
  7. Longest Common Subsequence
  8. Knapsack Problems
  9. Maximum-Weight Independent Set in Trees
  10. DP versus Greedy Algorithms
  11. Common Mistakes
  12. Official CS 161 References

What Is Dynamic Programming?

Dynamic programming solves a large problem by:

  1. Breaking it into smaller subproblems.
  2. Solving each subproblem once.
  3. Storing its solution in a table or cache.
  4. Combining stored solutions to solve larger subproblems.

Stanford describes DP as a meta-technique , not a single algorithm: it is a general method for designing algorithms when a problem has suitable recursive structure.stanford-cs161.github+

Two required properties

A problem is suitable for DP when it has:

Property Meaning

Optimal substructure An optimal solution contains optimal solutions to subproblems

Overlapping subproblems The same subproblems recur many times

Stanford’s notes state that analyzing these two properties is the main step in solving a DP problem.see.stanford+

The DP Recipe

Stanford’s CS 161 gives the following five-step recipe:web.stanford

  1. Identify optimal substructure. Determine how an optimal solution relates to optimal solutions of smaller subproblems.
  2. Find a recursive formulation. Define a recurrence for the value of the optimal solution.
  3. Use dynamic programming to compute the value. Fill a table in an order that ensures dependencies are already available.
  4. Track extra information if needed. Store parent pointers or choices if you need to reconstruct the actual solution.
  5. Implement the algorithm. Translate the recurrence and table-filling order into code.

Example template

For many DP problems:

DP[i]=best value using the first i itemsDP[i] = \text{best value using the first } i \text{ items}DP[i]=best value using the first i items

or:

DP[i][j]=best value for a subproblem indexed by i and jDP[i][j] = \text{best value for a subproblem indexed by } i \text{ and } jDP[i][j]=best value for a subproblem indexed by i and j

The final answer is usually stored in the last table cell, such as DP[n]DP[n]DP[n] or DP[m][n]DP[m][n]DP[m][n].stanford-cs161.github+

Memoization versus Tabulation

Approach Also called How it works Typical implementation

Memoization Top-down DP Solve recursively; cache results Recursion plus dictionary/array

Tabulation Bottom-up DP

Fill table from smallest subproblems upward Iterative loops

This can be reduced to Θ(1)\Theta(1)Θ(1) space because only the previous two values are needed.

Bellman-Ford

Bellman-Ford computes shortest paths from a single source sss in a graph with negative edge weights, assuming no negative-weight cycle is reachable from sss. Stanford CS 161 presents it as a DP algorithm.see.stanford+

DP definition

Let:

d(k)[v]=shortest-path distance from s to v using at most k edgesd^{(k)}[v] = \text{shortest-path distance from } s \text{ to } v \text{ using at most } k \text{ edges}d(k)[v]=shortest- path distance from s to v using at most k edges

Base case:

d(0)[s]=0,d(0)[v]=∞ for v≠sd^{(0)}[s] = 0, \qquad d^{(0)}[v] = \infty \text{ for } v \ne sd(0)[s]=0,d(0)[v]=∞ for v s

Recurrence:

d(k)[v]=min(u,v) ∈E{d(k−1)[u]+w(u,v)}d^{(k)}[v] = \min_{(u,v) \in E} \left{ d^{(k-1)}[u] + w(u,v) \right}d(k)[v]=(u,v)∈Emin{d(k−1)[u]+w(u,v)}

see.stanford+

Algorithm

text BELLMAN-FORD(G, s): for each vertex v: d[v] = infinity

d[s] = 0

for k = 1 to n - 1: for each edge (u, v) in E: if d[u] + w(u, v) < d[v]: d[v] = d[u] + w(u, v)

Runtime

The algorithm performs n−1n - 1n−1 rounds and examines all mmm edges in each round:

O(mn)O(mn)O(mn)

Stanford’s notes state this runtime explicitly.see.stanford+

Negative-cycle detection

After n−1n - 1n−1 rounds, perform one additional relaxation pass. If any edge can still be relaxed, a negative-weight cycle is reachable from the source.see.stanford+

Floyd-Warshall

Floyd-Warshall computes shortest paths between all pairs of vertices.

DP definition

Let:

D(k)[i][j]D^{(k)}[i][j]D(k)[i][j]

be the shortest-path distance from iii to jjj using only intermediate vertices from {1,2,…,k}{1, 2, \ldots, k}{1,2,…,k}.

Base case:

D(0)[i][j]={0if i=jw(i,j)if edge (i,j) exists∞otherwiseD^{(0)}[i][j] = \begin{cases} 0 & \text{if } i = j \ w(i,j) & \text{if edge } (i,j) \text{ exists} \ \infty & \text{otherwise} \end{cases}D(0)[i][j]=⎩⎨⎧0w(i,j)∞if i=jif edge (i,j) existsotherwise

Recurrence:

D(k)[i][j]=min(D(k−1)[i][j],D(k−1)[i][k]+D(k−1)[k][j])D^{(k)}[i][j] = \min \left( D^{(k- 1)}[i][j], D^{(k-1)}[i][k] + D^{(k-1)}[k][j] \right)D(k)[i][j]=min(D(k−1)[i][j],D(k−1)[i][k]+D(k−1)[k][j])

see.stanford+

Runtime

There are n2n^2n2 table entries, and each update takes constant time:

C[0][j] = 0

for i = 1 to m: for j = 1 to n: if X[i] = Y[j]: C[i][j] = C[i - 1][j - 1] + 1 else: C[i][j] = max(C[i - 1][j], C[i][j - 1])

return C[m][n]

Runtime

There are (m+1)(n+1)(m + 1)(n + 1)(m+1)(n+1) table entries, each computed in constant time:

Θ(mn)\Theta(mn)Θ(mn)

Space:

Θ(mn)\Theta(mn)Θ(mn)

This can be reduced to Θ(min(m,n)) \Theta(\min(m,n))Θ(min(m,n)) space if only the LCS length is needed.web.stanford+

Knapsack Problems

In the Knapsack problem, there are nnn items. Item iii has weight wiw_iwi and value viv_ivi. The knapsack has capacity WWW.stanford-cs161.github+

Unbounded Knapsack

Each item may be used any number of times.

Let:

K(x)=maximum value achievable with capacity xK(x) = \text{maximum value achievable with capacity } xK(x)=maximum value achievable with capacity x

Base case:

K(0)=0K(0) = 0K(0)=

Recurrence:

K(x)=maxi:wi≤x{K(x−wi)+vi}K(x) = \max_{i : w_i \le x} \left{ K(x - w_i) + v_i \right}K(x)=i:wi≤xmax{K(x−wi)+vi}

web.stanford+

Runtime:

O(nW)O(nW)O(nW)

0/1 Knapsack

Each item may be used at most once.

Let:

K[x][j]=maximum value using capacity x and only the first j itemsK[x][j] = \text{maximum value using capacity } x \text{ and only the first } j \text{ items}K[x][j]=maximum value using capacity x and only the first j items

Base cases:

K[x]=0,K[j]=0K[x] = 0, \qquad K[j] = 0K[x]=0,K[j]=

Recurrence:

K[x][j]={K[x][j−1]if wj>xmax(K[x][j−1],K[x−wj][j−1]+vj)otherwiseK[x][j] = \begin{cases} K[x][j - 1] & \text{if } w_j > x \ \max(K[x][j - 1], K[x - w_j][j - 1] + v_j) & \text{otherwise} \end{cases}K[x][j]={K[x][j−1]max(K[x][j−1],K[x−wj][j−1]+vj)if wj>xotherwise

web.stanford

Runtime:

O(nW)O(nW)O(nW)

Space:

O(nW)O(nW)O(nW)

This can be reduced to O(W)O(W)O(W) space by processing items one at a time and updating the capacity array in decreasing order.

Key distinction

Problem Item reuse DP dimension

DP versus Greedy Algorithms

Feature Dynamic programming Greedy algorithm

Decision strategy

Considers multiple subproblem solutions Makes one locally optimal choice

Subproblems Often overlapping May or may not overlap

Correctness proof

Optimal substructure and recurrence

Greedy-choice property and exchange argument

Typical runtime Polynomial in table size Often O(nlogn)O(n \log n)O(nlogn) or O(n)O(n)O(n)

Example 0/1 Knapsack Activity selection

A greedy algorithm may fail when a locally optimal choice prevents a globally optimal solution. DP avoids this by considering all relevant subproblem outcomes.stanford-cs161.github+

Common Mistakes

Mistake 1: Defining the wrong state

The DP state must contain enough information to make future decisions.

For 0/1 Knapsack, K[x]K[x]K[x] alone is insufficient because it does not track which items have already been used. The correct state is:

K[x][j]K[x][j]K[x][j]

where xxx is remaining capacity and jjj is the number of items considered.web.stanford

Mistake 2: Forgetting base cases

Every DP table needs base cases. For LCS:

C[i]=C[j]=0C[i] = C[j] = 0C[i]=C[j]=

For Bellman-Ford:

d(0)[s]=0d^{(0)}[s] = 0d(0)[s]=

and every other initial distance is infinity.see.stanford+

Mistake 3: Filling the table in the wrong order

A DP table must be filled so that every dependency is already computed.

For LCS, fill rows from top to bottom and columns from left to right. For Bellman-Ford, compute d(k)d^{(k)}d(k) using only d(k−1)d^{(k-1)}d(k−1).stanford-cs161.github+

Mistake 4: Confusing subsequence with substring

A subsequence preserves order but may skip characters.

A substring must be contiguous.

LCS uses subsequences, not substrings.stanford-cs161.github+

Mistake 5: Ignoring reconstruction

If the problem asks for the actual solution, not just its value, store predecessor or choice information while filling the table. Stanford’s DP recipe includes this as Step 4.web.stanford

Official CS 161 References

Topic Official Stanford resource Topic Official Stanford resource

Dynamic programming: Bellman-Ford and Floyd-Warshall Winter 2026 Lecture 12 notes stanford-cs161.github

Bellman-Ford and Floyd-Warshall Winter 2022 Lecture 12 notes see.stanford

LCS, Knapsack, independent set Winter 2023 Lecture 13 notes stanford-cs161.github

More DP: LCS, Knapsack, independent set Winter 2025 Lecture 13 notes stanford-cs161.github

DP recipe and recurrence examples Winter 2026 Lecture 13 slides web.stanford

DP as a meta-technique Spring 2015 Lecture 16 stanford-cs161.github

Course lecture index Winter 2025 lectures stanford- cs161.github

Quick Revision Card