我在读动态编程中的矩阵链乘法,它有一个简单的递归解决方案,它具有指数运行时间。
http://www.geeksforgeeks.org/dynamic-programming-set-8-matrix-chain-multiplication/
尽管有动态程序。解决方案(上面链接中的代码)的运行时复杂度为O(n^3),但如果我们保留一个2d数组来存储重叠子问题的结果,它的运行时是否与dp解决方案相同?
public class MatrixChain {
public static void main(String... args) throws IOException {
new MatrixChain().job();
}
private void job() {
int arr[] = new int[]{40, 20, 30, 10, 30};
int[][] dp = new int[5][5];
for (int[] x : dp)
Arrays.fill(x, -1);
int min = findMin(arr, 1, arr.length - 1, dp);
System.out.println(min);
}
private int findMin(int[] arr, int i, int j, int dp[][]) {
if (i == j) return 0;
int min = Integer.MAX_VALUE;
for (int k = i; k < j; k++) {
int fp;
if (dp[i][k] == -1)
dp[i][k] = fp = findMin(arr, i, k, dp);
else fp = dp[i][k];
int lp;
if (dp[k + 1][j] == -1)
dp[k + 1][j] = lp = findMin(arr, k + 1, j, dp);
else
lp = dp[k + 1][j];
int sum = fp + lp + arr[i - 1] * arr[k] * arr[j];
if (sum < min)
min = sum;
}
return min;
}
}
谢谢!
是的,它会有。编写函数是迭代的还是递归的并不重要。重要的是,你要记住你的结果。你确实这么做了。
尽管我有一些优化:
private int findMin(int[] arr, int i, int j, int dp[][]) {
if (i == j)
return 0;
/* Immediate look-up in dp */
if (dp[i][j] != -1)
return dp[i][j];
/* Otherwise compute the number, much shorter since you don't
have to worry about reading from dp and saving it to dp. */
int min = Integer.MAX_VALUE;
for (int k = i; k < j; k++) {
int fp = findMin(arr, i, k, dp);
int lp = findMin(arr, k + 1, j, dp);
int sum = fp + lp + arr[i - 1] * arr[k] * arr[j];
if (sum < min)
min = sum;
}
/* Now save the result */
dp[i][j] = min;
return min;
}