【问题标题】:All possible paths from top left to bottom right of a mXn matrixmXn 矩阵从左上角到右下角的所有可能路径
【发布时间】:2019-09-17 23:59:41
【问题描述】:

我正在通过this leetcode problem for going from top left to bottom right.

有多少种可能的独特路径?

通过存储每个索引的结果,我能够理解这种动态编程方法。

  public int uniquePaths(int m, int n) {   
        int count[][] = new int[m][n]; 
        for (int i = 0; i < m; i++) 
            count[i][0] = 1; 
        for (int j = 0; j < n; j++) 
            count[0][j] = 1; 
        for (int i = 1; i < m; i++)  { 
            for (int j = 1; j < n; j++) {
                count[i][j] = count[i-1][j] + count[i][j-1]; //+ count[i-1][j-1]; 
            }
        } 
        return count[m-1][n-1];       
        // if (m == 1 || n == 1)  return 1;    
        // return  uniquePaths(m-1, n) + uniquePaths(m, n-1); 
    }

但是,我发现了这个我无法理解的解决方案。

  public int uniquePaths(int m, int n) {   
         int[] dp = new int[n]; 
         dp[0] = 1; 

       for (int i = 0; i < m; i++) { 
         for (int j = 1; j < n; j++) { 
           dp[j] += dp[j - 1]; 
         } 
       } 
       return dp[n - 1]; 
    }

这里是the link to the problem

有人可以解释第二个解决方案吗?

【问题讨论】:

  • unique 路径是什么意思? 最短路径?还是所有可能的路径?对于最短路径,金额为m * n - 1

标签: java algorithm recursion dynamic-programming


【解决方案1】:

在您的第一个解决方案中,整个矩阵已被填充,但您会注意到 count[i][j] = count[i-1][j] + count[i][j-1] 中的每一行仅使用一次。

所以你基本上可以在使用后丢弃它。第二种解决方案正是这样做的。我们可以只用一行来执行所有的计算。

当我们填写它时,我们可以将代码替换为count[0][j] = count[0][j] + count[0][j-1],基本上就是count[0][j] += count[0][j-1]

注意

    for (int i = 0; i < m; i++) 
        count[i][0] = 1; 

没用,我们总是覆盖那些单元格。

还有

for (int j = 0; j < n; j++) 
   count[0][j] = 1; 

等价于

dp[0][0] = 1;
for (int j = 1; j < n; j++) { 
   dp[0][j] += dp[0][j - 1]; 
}

在第二个示例中我们已经将其作为内部循环。

【讨论】:

    【解决方案2】:

    基本上,在第二种解决方案中,我们通过利用用于节省前一行计算的空间来优化空间复杂度。因为,在计算当前行的值之后,它在jth位置的值只会被下一行jth位置的值消耗。
    所以,dp[j] += dp[j - 1];
    => dp[j] = dp[j] + dp[j - 1]
    => dp value of jth column of current row = dp value at jth pos in prev row + dp value of j-1 th pos of current row

    这里,前一行的值jth 被当前行的jth 位置的值覆盖。
    谢谢!

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多