1
1
package com .thealgorithms .dynamicprogramming ;
2
2
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
+ */
9
16
public final class MatrixChainRecursiveTopDownMemoisation {
10
17
private MatrixChainRecursiveTopDownMemoisation () {
11
18
}
12
19
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
+ */
13
29
static int memoizedMatrixChain (int [] p ) {
14
30
int n = p .length ;
15
31
int [][] m = new int [n ][n ];
@@ -21,6 +37,17 @@ static int memoizedMatrixChain(int[] p) {
21
37
return lookupChain (m , p , 1 , n - 1 );
22
38
}
23
39
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
+ */
24
51
static int lookupChain (int [][] m , int [] p , int i , int j ) {
25
52
if (i == j ) {
26
53
m [i ][j ] = 0 ;
@@ -38,11 +65,4 @@ static int lookupChain(int[][] m, int[] p, int i, int j) {
38
65
}
39
66
return m [i ][j ];
40
67
}
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
- }
48
68
}
0 commit comments