11package com .thealgorithms .dynamicprogramming ;
22
3- // Matrix-chain Multiplication
4- // Problem Statement
5- // we have given a chain A1,A2,...,Ani of n matrices, where for i = 1,2,...,n,
6- // matrix Ai has dimension pi−1 ×pi
7- // , fully parenthesize the product A1A2 ···An in a way that
8- // minimizes the number of scalar multiplications.
3+ /**
4+ * The MatrixChainRecursiveTopDownMemoisation class implements the matrix-chain
5+ * multiplication problem using a top-down recursive approach with memoization.
6+ *
7+ * <p>Given a chain of matrices A1, A2, ..., An, where matrix Ai has dimensions
8+ * pi-1 × pi, this algorithm finds the optimal way to fully parenthesize the
9+ * product A1A2...An in a way that minimizes the total number of scalar
10+ * multiplications required.</p>
11+ *
12+ * <p>This implementation uses a memoization technique to store the results of
13+ * subproblems, which significantly reduces the number of recursive calls and
14+ * improves performance compared to a naive recursive approach.</p>
15+ */
916public final class MatrixChainRecursiveTopDownMemoisation {
1017 private MatrixChainRecursiveTopDownMemoisation () {
1118 }
1219
20+ /**
21+ * Calculates the minimum number of scalar multiplications needed to multiply
22+ * a chain of matrices.
23+ *
24+ * @param p an array of integers representing the dimensions of the matrices.
25+ * The length of the array is n + 1, where n is the number of matrices.
26+ * @return the minimum number of multiplications required to multiply the chain
27+ * of matrices.
28+ */
1329 static int memoizedMatrixChain (int [] p ) {
1430 int n = p .length ;
1531 int [][] m = new int [n ][n ];
@@ -21,6 +37,17 @@ static int memoizedMatrixChain(int[] p) {
2137 return lookupChain (m , p , 1 , n - 1 );
2238 }
2339
40+ /**
41+ * A recursive helper method to lookup the minimum number of multiplications
42+ * for multiplying matrices from index i to index j.
43+ *
44+ * @param m the memoization table storing the results of subproblems.
45+ * @param p an array of integers representing the dimensions of the matrices.
46+ * @param i the starting index of the matrix chain.
47+ * @param j the ending index of the matrix chain.
48+ * @return the minimum number of multiplications needed to multiply matrices
49+ * from i to j.
50+ */
2451 static int lookupChain (int [][] m , int [] p , int i , int j ) {
2552 if (i == j ) {
2653 m [i ][j ] = 0 ;
@@ -38,11 +65,4 @@ static int lookupChain(int[][] m, int[] p, int i, int j) {
3865 }
3966 return m [i ][j ];
4067 }
41-
42- // in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5
43- // respectively output should be Minimum number of multiplications is 38
44- public static void main (String [] args ) {
45- int [] arr = {1 , 2 , 3 , 4 , 5 };
46- System .out .println ("Minimum number of multiplications is " + memoizedMatrixChain (arr ));
47- }
4868}
0 commit comments