-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
40 lines (35 loc) · 1.22 KB
/
Copy pathsolution.java
File metadata and controls
40 lines (35 loc) · 1.22 KB
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
class Solution {
public String matrixChainOrder(int arr[]) {
int n = arr.length;
int N = n - 1; // number of matrices
long[][] dp = new long[N + 1][N + 1];
int[][] split = new int[N + 1][N + 1];
// for len = 2..N
for (int len = 2; len <= N; len++) {
for (int i = 1; i + len - 1 <= N; i++) {
int j = i + len - 1;
dp[i][j] = Long.MAX_VALUE;
for (int k = i; k < j; k++) {
long cost = dp[i][k] + dp[k + 1][j]
+ 1L * arr[i - 1] * arr[k] * arr[j];
if (cost < dp[i][j]) {
dp[i][j] = cost;
split[i][j] = k;
}
}
}
}
// recursive builder
return build(1, N, split);
}
private String build(int i, int j, int[][] split) {
if (i == j) {
char ch = (char) ('A' + (i - 1));
return String.valueOf(ch);
}
int k = split[i][j];
String left = build(i, k, split);
String right = build(k + 1, j, split);
return "(" + left + right + ")";
}
}