-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmatrix_chain.cpp
64 lines (50 loc) · 1.29 KB
/
matrix_chain.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<bits/stdc++.h>
using namespace std;
class Solution{
public:
int dp[27][27];
int bracket[27][27];
string str;
char ch;
void printParenthesis(int i, int j)
{
if (i == j){
str += ch;
ch++;
return;
}
str += '(';
printParenthesis(i, bracket[i][j]);
printParenthesis(bracket[i][j] + 1, j);
str += ')';
}
int solve( int arr[], int i, int j)
{
if(i>=j) return 0;
if(dp[i][j]!=-1)
{
return dp[i][j];
}
int ans= INT_MAX;
for(int k=i; k<=j-1; k++)
{
int temp= solve(arr, i, k)+ solve(arr, k+1, j)+ (arr[i-1]*arr[k]*arr[j]);
if(temp<ans)
{
ans= temp;
bracket[i][j]= k;
}
}
dp[i][j]= ans;
return ans;
}
string matrixChainOrder(int p[], int n){
memset(dp, -1, sizeof(dp));
memset(bracket, -1, sizeof(bracket));
int cost= solve(p, 1, n-1);
ch = 'A';
str="";
printParenthesis(1, n-1);
return str;
}
};