Algorithms · Matrix Chain Multiplication Worked Table, Catalan Counting and Optimal BST
Full worked table for p = ⟨10, 30, 5, 60⟩
Here matrices:
- :
- :
- :
So .
Length 1 (base case)
| cell | value |
|---|---|
| 0 | |
| 0 | |
| 0 |
Length 2
: only . ; . So , .
: only . ; . So , .
Length 3
: two candidates, and .
- : . ; . Total .
- : . ; . Total .
Minimum is at . So , .
The complete table
| 0 | 1500 | 4500 | |
| — | 0 | 9000 | |
| — | — | 0 |
The complete table
| — | 1 | 2 | |
| — | — | 2 | |
| — | — | — |
Reconstructing the parenthesization
Start at : means split as .
- Left part : means .
- Right part : single matrix.
So the optimal parenthesization is .
Verification by direct multiplication:
- : times costs , result is .
- : times costs , result is .
- Total . ✓
Compare with the other order :
- : times costs , result .
- : times costs .
- Total .
So the optimal cost is 4500, and the optimal parenthesization is .
Counting parenthesizations: the Catalan number
The number of distinct ways to fully parenthesize a product of matrices is the -th Catalan number:
Equivalently, writing for the -th Catalan number (with ):
The recurrence is and for (e.g. ).
Check the values:
- matrices: . ✓ (We saw exactly two: and .)
- matrices: . ✓
- matrices: . ✓
| (matrices) | value | |
|---|---|---|
| 1 | 1 | |
| 2 | 1 | |
| 3 | 2 | |
| 4 | 5 | |
| 5 | 14 | |
| 6 | 42 |
Why this matters: the brute-force algorithm that tries every parenthesization is , which grows like — exponential. The DP is polynomial, which is the whole point.
Complexity of the DP
- Number of distinct subproblems: pairs with , i.e. .
- Work per subproblem: the min over from to , at most choices, so .
- Total time: .
- Space: the and tables are each , so .
| Quantity | Bound |
|---|---|
| Subproblems | |
| Time per subproblem | |
| Total time | |
| Space | |
| Brute force (all parenthesizations) | , exponential |