此代码取自一本通用算法书籍。这本书使用了一个从 1 开始的数组,而不是 0 form
但从 0 开始 for p
。我该如何解决?
这些是错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at MMC_Test.MemoizedMatrixChain(MMC_Test.java:8)
at MMC_Test.main(MMC_Test.java:36)
和代码在这里
public class MMC_Test {
public static int MemoizedMatrixChain(int[] p) {
int n = p.length - 1;
int[][] m = new int[n][n];
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
m[i][j] = Integer.MAX_VALUE;
}
}
return lookUpChain(m, p, 1, n);
}// MemoizedMatrixChain
public static int lookUpChain(int[][] m, int[] p, int i, int j) {
if (m[i][j] > Integer.MAX_VALUE) {
return m[i][j];
}
if (i == j) {
m[i][j] = 0;
} else {
for (int k = i; k <= j - 1; k++) {
int q = lookUpChain(m, p, i, k)
+ lookUpChain(m, p, k + 1, j)
+ p[i - 1] * p[k] * p[j];
if (q < m[i][j]) {
m[i][j] = q;
}
}
}
return m[i][j];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = { 30, 35, 15, 5, 10, 20, 25 };
int result = MemoizedMatrixChain(arr);
System.out.println(result);
}// main
}