forked from Masked-coder11/gfg-POTD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
27.01.2024.cpp
42 lines (31 loc) · 1.11 KB
/
27.01.2024.cpp
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
// User function Template for C++
class Solution{
public:
pair<string,int> solve(int p[], int n, int i, int j, vector<vector<pair<string,int>>>&v){
if(i==j){
string s="";
s+='A'+i-1;
return {s,0};
}
if(v[i][j].second!=-1) return v[i][j];
int mini=INT_MAX;
string sr="";
for(int k=i;k<=j-1;k++){
pair<string,int>left=solve(p, n, i, k,v);
pair<string,int>right=solve(p,n,k+1,j,v);
int steps =left.second + right.second + p[i-1]*p[k]*p[j];
if(steps<mini){
sr='('+left.first+right.first+')';
mini=steps;
}
}
return v[i][j]={sr, mini};
}
string matrixChainOrder(int p[], int n){
// code here
vector<vector<pair<string,int>>>v(n, vector<pair<string,int>>(n,{"",-1}));
pair<string,int> operations = solve(p, n , 1, n-1, v);
//forming the name
return operations.first;
}
};