-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create Brackets in Matrix Chain Multiplication
- Loading branch information
1 parent
de8d6c9
commit d6bf12a
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}; | ||
} | ||
}; |