【问题标题】:Interview Question on Algorithms regarding Matrices关于矩阵算法的面试问题
【发布时间】:2019-10-13 16:14:15
【问题描述】:

为您提供了一个包含整数值的 N*M 矩阵。你的任务是从每一行中选择一个整数,使这些整数的总和最大。但是,您不能从同一列的相邻行中选择两个整数。

我怎样才能在小于 O(N^M)(或 O(M^N))的时间内解决这个问题?

【问题讨论】:

  • 提示:将此视为一个图形问题,您希望在其中找到最短路径。但是路径的权重在这里是max X - xmax X 是矩阵的最大值,x 是单元格的值。因此,您可以使其 O(n^2 m^2).
  • 你可以在 O(N*M) 时间内通过动态规划来做到这一点。

标签: algorithm matrix data-structures


【解决方案1】:

我想出了两种可能的解决方案:1. 使用递归,2. 使用 DP。

1。使用递归

我想你已经有了这个解决方案。我做了一个递归函数,它遍历矩阵中的每一行并为每一列调用递归。正如您所提到的,时间复杂度将是 O(M^N),其中 N 是行数,M 是列数。

int getMaxSum(int[][] matrix) {
    return getMax(matrix, 0, -1);
}

int getMax(int[][] matrix, int row, int prevCol) {
    if (row >= matrix.length) return 0;

    int result = Integer.MIN_VALUE;
    for (int i = 0; i < matrix[row].length; i++) {
        if (i == prevCol) continue;

        int sum = getMax(matrix, row+1, i) + matrix[row][i];
        result = Math.max(result, sum);
    }

    return result;
}

2。使用 DP

我可以使用 DP 来跟踪每一列直到某一行的最大总和,而不是递归地遍历所有行和列。例如,DP[r][c] 可以在列 c 到行 r 处具有最大可能总和。为了实现这一点,我需要遍历输入矩阵中的所有行和列,并且在每个索引处,我还需要遍历前一行(不包括同一列)的最大可能总和。这将导致 O(N*M^2) 的时间复杂度,其中 N 是行数,M 是列数。

int getMaxSum(int[][] matrix) {
    if (matrix.length == 0) return 0;

    int[][] maxSumsDP = new int[matrix.length+1][matrix[0].length];
    for (int r = 1; r <= matrix.length; r++) {
        for (int c = 0; c < matrix[r-1].length; c++) {
            int maxPrev = Integer.MIN_VALUE;
            for (int i = 0; i < maxSumDP[r-1].length; i++) {
                if (i == c) continue;

                maxPrev = Math.max(maxPrev, maxSumsDP[r-1][i]);
            }
            maxSumsDP[r][c] = maxPrev + matrix[r-1][c];
        }
    }

    int result = maxSumsDP[maxSumsDP.length-1][0];
    for (int i = 1; i < maxSumsDP[maxSumsDP.length-1].length; i++) {
        result = Math.max(result, maxSumsDP[maxSumsDP.length-1][i]);
    }
    return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-13
    • 2011-06-09
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    相关资源
    最近更新 更多