【问题标题】:Maximum non negative product in a matrix矩阵中的最大非负积
【发布时间】:2022-07-02 11:36:36
【问题描述】:

我正在尝试解决 leetcode.com 上的以下problem

我发现resource 提出了类似的问题,但没有得出任何合理的结论。

我能够提出一个递归回溯解决方案,但是对于一个非常大的矩阵,它在最后 5 个测试用例中失败了。我感觉有一些重复的工作,但不知道是什么。

逻辑的写法,苦苦摸索

  1. 我需要记住的内容
  2. 如何调整我的逻辑以便我在每一步都进行优化

感谢任何帮助

class Solution {
    private long max = -1;
    public int maxProductPath(int[][] grid) {
        long mod=1000000007;
        int rows = grid.length;
        int cols = grid[0].length;
        int cp = 1;
        pathFinder(grid, rows, cols, cp, rows-1, cols-1);
        if(max < 0 ) return -1;
        return (int)(max % mod);
    }
    
    public void pathFinder(int[][]grid, int rows, int cols, long cp, int r, int c){
        if(r >= rows || c >= cols || r < 0 || c < 0){
            return;
        }
        if(r == 0 && c  == 0){
            this.max = Math.max(cp * grid[r][c] , this.max);
            return;
        }
        pathFinder(grid, rows, cols, cp * grid[r][c], r - 1, c);
        pathFinder(grid, rows, cols, cp * grid[r][c], r , c - 1);
    }
}

【问题讨论】:

    标签: algorithm recursion graph dynamic-programming backtracking


    【解决方案1】:

    您的逻辑是正确的,但由于您没有使用 memoization,因此多次重复调用会导致超时。

    您基本上需要记住从(r,c) 开始的路径的最大产品,所以您的函数看起来像

    pathFinder(...args, dp[][]) {
      if (dp[row][col] != null) return dp[row][col]
      else {
        // compute answer
        dp[row][col] = answer
      }
    }
    

    【讨论】:

    • 你的意思是这样的吗? productUP = pathFinder(grid, rows, cols, cp * grid[r][c], r - 1, c); productLEFT = pathFinder(grid, rows, cols, cp * grid[r][c], r, c - 1);返回 Math.max (productUP, productLEFT);
    • @Spindoctor 不行,你需要添加一个 dp/memoization 表
    【解决方案2】:

    这似乎与经典的右下动态程序有点不同。问题是我们需要两个状态,因为我们的最大值可以由两个正数或两个负数构成。一般:

    if grid[i][j] < 0:
      dp[i][j][positive] = max(
        grid[i][j] * dp[i-1][j][negative],
        grid[i][j] * dp[i][j-1][negative]
      )
      dp[i][j][negative] = min(
        grid[i][j] * dp[i-1][j][positive],
        grid[i][j] * dp[i][j-1][positive]
      )
    
    if grid[i][j] > 0:
      dp[i][j][positive] = max(
        grid[i][j] * dp[i-1][j][positive],
        grid[i][j] * dp[i][j-1][positive]
      )
      dp[i][j][negative] = min(
        grid[i][j] * dp[i-1][j][negative],
        grid[i][j] * dp[i][j-1][negative]
      )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-17
      • 2015-10-11
      • 2021-01-12
      • 2018-05-12
      • 2019-04-14
      • 2014-09-04
      • 2015-04-12
      • 1970-01-01
      相关资源
      最近更新 更多