动态规划矩阵链乘法

时间:2016-07-19 17:26:53

标签: java dynamic-programming

我正在阅读动态编程中的矩阵链乘法, 它有一个天真的递归解决方案,具有指数运行时。

http://www.geeksforgeeks.org/dynamic-programming-set-8-matrix-chain-multiplication/

虽然有动态编程。解决方案(上面链接中的代码),其运行时复杂度为O(n ^ 3),但如果我们保留一个二维数组来存储重叠子问题的结果,它是否与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;
    }
}

谢谢!

1 个答案:

答案 0 :(得分:1)

是的,它会有。如果你编写迭代或递归函数并不重要。重要的是,你记住你的结果。那就是你做的。

虽然我有一些优化:

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;
}