Improve docs, remove main, add tests for `MatrixChainRecursiveTopDo… (#5659)

This commit is contained in:
Hardik Pawar
2024-10-12 12:21:41 +05:30
committed by GitHub
parent eba6823c3a
commit 138793df1d
3 changed files with 102 additions and 13 deletions

View File

@ -1,15 +1,31 @@
package com.thealgorithms.dynamicprogramming;
// Matrix-chain Multiplication
// Problem Statement
// we have given a chain A1,A2,...,Ani of n matrices, where for i = 1,2,...,n,
// matrix Ai has dimension pi1 ×pi
// , fully parenthesize the product A1A2 ···An in a way that
// minimizes the number of scalar multiplications.
/**
* The MatrixChainRecursiveTopDownMemoisation class implements the matrix-chain
* multiplication problem using a top-down recursive approach with memoization.
*
* <p>Given a chain of matrices A1, A2, ..., An, where matrix Ai has dimensions
* pi-1 × pi, this algorithm finds the optimal way to fully parenthesize the
* product A1A2...An in a way that minimizes the total number of scalar
* multiplications required.</p>
*
* <p>This implementation uses a memoization technique to store the results of
* subproblems, which significantly reduces the number of recursive calls and
* improves performance compared to a naive recursive approach.</p>
*/
public final class MatrixChainRecursiveTopDownMemoisation {
private MatrixChainRecursiveTopDownMemoisation() {
}
/**
* Calculates the minimum number of scalar multiplications needed to multiply
* a chain of matrices.
*
* @param p an array of integers representing the dimensions of the matrices.
* The length of the array is n + 1, where n is the number of matrices.
* @return the minimum number of multiplications required to multiply the chain
* of matrices.
*/
static int memoizedMatrixChain(int[] p) {
int n = p.length;
int[][] m = new int[n][n];
@ -21,6 +37,17 @@ public final class MatrixChainRecursiveTopDownMemoisation {
return lookupChain(m, p, 1, n - 1);
}
/**
* A recursive helper method to lookup the minimum number of multiplications
* for multiplying matrices from index i to index j.
*
* @param m the memoization table storing the results of subproblems.
* @param p an array of integers representing the dimensions of the matrices.
* @param i the starting index of the matrix chain.
* @param j the ending index of the matrix chain.
* @return the minimum number of multiplications needed to multiply matrices
* from i to j.
*/
static int lookupChain(int[][] m, int[] p, int i, int j) {
if (i == j) {
m[i][j] = 0;
@ -38,11 +65,4 @@ public final class MatrixChainRecursiveTopDownMemoisation {
}
return m[i][j];
}
// in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5
// respectively output should be Minimum number of multiplications is 38
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
System.out.println("Minimum number of multiplications is " + memoizedMatrixChain(arr));
}
}