Complete the code to initialize the minimum cost to zero for a single matrix.
for (int i = 1; i <= n; i++) { dp[i][i] = [1]; }
For a single matrix, no multiplication is needed, so the cost is zero.
Complete the code to calculate the cost of multiplying two matrix chains split at k.
int cost = dp[i][k] + dp[k + 1][j] + [1] * [2] * [3];
The cost formula multiplies the dimensions of the matrices involved: p[i-1] * p[k] * p[j]. Here, the first dimension is p[i-1].
Fix the error in the loop that sets the chain length for matrix multiplication.
for (int len = 2; len <= [1]; len++) { for (int i = 1; i <= n - len + 1; i++) { int j = i + len - 1; // compute dp[i][j] } }
The chain length should go up to n, the total number of matrices.
Fill both blanks to update the minimum multiplication cost correctly.
for (int k = i; k < j; k++) { int cost = dp[i][k] + dp[k + 1][j] + p[i - 1] * p[k] * p[j]; if (cost [1] dp[i][j]) { dp[i][j] = [2]; } }
If the new cost is less than the current dp[i][j], update dp[i][j] with the new cost.
Fill all three blanks to complete the recursive memoized function for matrix chain multiplication.
int matrixChainMemo(int i, int j, vector<int>& p, vector<vector<int>>& dp) {
if (i == j) return [1];
if (dp[i][j] != -1) return dp[i][j];
dp[i][j] = [2];
for (int k = i; k < j; k++) {
int cost = matrixChainMemo(i, k, p, dp) + matrixChainMemo(k + 1, j, p, dp) + p[i - 1] * p[k] * p[j];
if (cost < dp[i][j]) dp[i][j] = [3];
}
return dp[i][j];
}Base case returns 0 cost for one matrix. Initialize dp[i][j] with INT_MAX. Update dp[i][j] with cost if smaller.
