-
Notifications
You must be signed in to change notification settings - Fork 0
/
34. Matrix Chain Multiplication Recursive
77 lines (53 loc) · 1.48 KB
/
34. Matrix Chain Multiplication Recursive
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
34 .Matrix Chain Multiplication Recursive
Video Link : https://youtu.be/kMK148J9qEE
GFG Problem Link : https://practice.geeksforgeeks.org/problems/matrix-chain-multiplication0303/1
Recursive Solution ;
------->>>>>>>>>>>------------>>>>>>>>>>>>________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 solve(int arr[], int i,int j)
{
// base condition
if(i>= j ){
return 0;
}
// to store the minimun answer
int mn= INT_MAX;
for(int k=i;k<j;k++)
{
//store the temporary potential answer
int temp= solve(arr,i,k) + solve(arr, k+1,j) + arr[i-1] * arr[k] * arr[j] ;
mn= min(temp, mn);
}
return mn;
}
int matrixMultiplication(int N, int arr[])
{
// code here
int i=1,j=N-1;
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