-
Notifications
You must be signed in to change notification settings - Fork 0
/
35 .Matrix chain multiplication Memoization
85 lines (56 loc) · 1.59 KB
/
35 .Matrix chain multiplication Memoization
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
35 . Matrix chain multiplication Memoization
Video Link : https://youtu.be/9uUVFNOT3_Y
GFG Practice link : https://practice.geeksforgeeks.org/problems/matrix-chain-multiplication0303/1
------->>>>>>>>>>>------------>>>>>>>>>>>>________CODE________<<<<<<<<<<<<------------<<<<<<<<<<<<<<<<<<<<<<<<<<<
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution{
public:
int dp[101][101];
int solve(int arr[], int i,int j)
{
if(i>= j ){
return 0;
}
// check if value is already present
if(dp[i][j]!=-1){
return dp[i][j];
}
int mn= INT_MAX;
for(int k=i;k<j;k++)
{
int temp= solve(arr,i,k) + solve(arr, k+1,j) + arr[i-1] * arr[k] * arr[j] ;
mn= min(temp, mn);
}
// before returnin store the value of dp[i][j] to further repeatitive calls
return dp[i][j]= mn;
}
int matrixMultiplication(int N, int arr[])
{
// code here
int i=1,j=N-1;
memset(dp,-1,sizeof(dp)) ;
int ans= solve(arr, i,j);
return ans;
}
};
//{ Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int N;
cin>>N;
int arr[N];
for(int i = 0;i < N;i++)
cin>>arr[i];
Solution ob;
cout<<ob.matrixMultiplication(N, arr)<<endl;
}
return 0;
}
// } Driver Code Ends