...
/Solution Review: The Matrix Chain Multiplication
Solution Review: The Matrix Chain Multiplication
In this lesson, we will solve the matrix chain multiplication problem with different techniques of dynamic programming.
Solution 1: Simple recursion #
Press + to interact
import numpy as npdef minMultiplications(dims):if len(dims) <= 2:return 0minimum = np.inffor i in range(1,len(dims)-1):minimum = min(minimum, minMultiplications(dims[0:i+1]) + minMultiplications(dims[i:]) +dims[0] * dims[-1] * dims[i])return minimumprint(minMultiplications([3, 3, 2, 1, 2]))
Explanation
We can easily imagine dims
to be a list of matrices. Then each recursive call tries to find the optimal placement of two parentheses between these matrices. So, let’s say we have the following sequence of matrices: . Each recursive call tries to place two parentheses, so we have the following possibilities: