Dynamic Programming21 sections · 916 units
Open in Course

Challenge: Matrix Chain Reconstruction

Finding optimal parenthesization

The DP gives minimum cost, but what's the optimal order? Track the split point. When computing dp[i][j]dp[i][j], record split[i][j]=ksplit[i][j] = k where the minimum occurs.

Reconstruct recursively: parenthesize(i,j)parenthesize(i, j) = "(" + parenthesize(i,split[i][j])parenthesize(i, split[i][j]) + parenthesize(split[i][j]+1,j)parenthesize(split[i][j]+1, j) + ")". For our example: split[1][3]=2split[1][3] = 2, so optimal is (A1A2)A3(A_1 \cdot A_2) \cdot A_3. Store the split point in a separate array. Reconstruct by recursively printing the optimal parenthesization.