Complete the code to initialize the DP table with zeros for matrix chain multiplication.
n = len(p) - 1 m = [[[1] for _ in range(n)] for _ in range(n)]
We initialize the DP table with zeros because initially, the cost of multiplying one matrix is zero.
Complete the code to set the chain length for the outer loop in matrix chain multiplication.
for L in range(2, [1] + 1):
The chain length L goes from 2 to n (number of matrices).
Fix the error in the code to calculate the minimum cost for multiplying matrices from i to j.
for k in range(i, j): cost = m[i][k] + m[k+1][j] + p[i]*p[k+1]*p[j+1] m[i][j] = min(m[i][j], [1])
We update m[i][j] with the minimum of its current value and the newly calculated cost.
Fill both blanks to correctly set the indices for the subproblems in matrix chain multiplication.
for i in range(0, n - [1] + 1): j = i + [2] - 1
i loops from 0 to n-L, and j is set to i+L-1 to cover the chain length L.
Fill all three blanks to complete the matrix chain multiplication function that returns the minimum multiplication cost.
def matrix_chain_order(p): n = len(p) - 1 m = [[0 for _ in range(n)] for _ in range(n)] for L in range(2, n + 1): for i in range(0, n - L + 1): j = i + L - 1 m[i][j] = float('inf') for k in range(i, j): cost = m[i][k] + m[k+1][j] + p[i] * p[k+1] * p[j+1] if cost < m[i][j]: m[i][j] = [1] return [2]
Update m[i][j] with the current cost if it's less, and finally return m[0][n-1] which holds the minimum cost for the full chain.
