DP table
- Algorithms course
- Advanced
- Lesson 22/56
- 4 min
Build a DP table for matrix chain.
DP table
The two-dimensional table m[i][j] stores the lowest cost of multiplying matrices from i to j. The diagonal m[i][i] = 0 because a single matrix needs no multiplication.
The table solves subproblems and reuses results in larger problems. This is the core of dynamic programming.
Table size
For n matrices the table is n × n. Initially all values are zero; not just the diagonal, every cell is zeroed.
Then subproblems are solved to fill the table. Short chains are computed first, then longer chains.
Practice init_table function
Write init_table(n). Return an n×n zero matrix. Print it with print(init_table(4)).
Starter code
def init_table(n):
# Return n×n zero matrixSample solution
def init_table(n):
# Return n×n zero matrix
return [[0] * n for _ in range(n)]
print(init_table(4))Expected output
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Diagonal value
m[i][i] = ____
m[i][i] = 0
Explanation: 0 is right.
2 What is the table size for three matrices?
- 3×3
- 2×2 Correct answer
- 4×4
- 5×5
Explanation: Three matrices mean four dimensions, so the table is 4×4.
3 DP table: match the terms
| Term | Meaning |
|---|---|
m[i][i] |
0 |
m[1][2] |
6000 |
m[2][3] |
24000 |
m[1][3] |
18000 |