Skip to content

Commit

Permalink
Create Brackets in Matrix Chain Multiplication
Browse files Browse the repository at this point in the history
  • Loading branch information
nidhiupman568 authored Jan 27, 2024
1 parent de8d6c9 commit d6bf12a
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions Brackets in Matrix Chain Multiplication
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution{
public:
pair<int,string> dp[27][27];
string matrixChainOrder(int p[], int n){
return f(1,n-1,p).second;
}

pair<int,string> f(int i,int j,int p[]){
if(i==j){
string curr = "";
curr += 'A' + i-1;
return {0,curr};
}

if(dp[i][j].second != "") return dp[i][j];

int val = INT_MAX;
string s = "";

for(int k=i;k<j;k++){
pair<int,string> a = f(i,k,p);
pair<int,string> b = f(k+1,j,p);
int q = p[i-1]*p[j]*p[k] + a.first + b.first;
if(q<val){
val = q;
s = "(" + a.second + b.second + ")";
}
}
return dp[i][j] = {val,s};
}
};

0 comments on commit d6bf12a

Please sign in to comment.