繁体   English   中英

矩阵中的最小成本路径

[英]minimum cost path in matrix

题 -

给定amxn网格填充非负数,找到从左上到右下的路径,最小化沿其路径的所有数字的总和。

注意:您只能在任何时间点向下或向右移动

我知道这是一个常见的问题,你们大多数人都会知道这个问题以及它的动态编程。 我在这里尝试递归代码,但我得到了正确的输出。 我的递归代码中缺少什么? 我不想要迭代或动态编程方法。 我正在努力建立自己的。

它显示错误的输出。

示例 -

1 2
1 1

它将输出设为2.其中答案为3。

谢谢。

def minPathSum(self, grid):
    """
    :type grid: List[List[int]]
    :rtype: int
    """
    def helper(i,j,grid,dp):
        if i >= len(grid) or j >= len(grid[0]):
            return 0
        print grid[i][j]

        return grid[i][j]+min(helper(i+1,j,grid,dp),helper(i,j+1,grid,dp))
    dp = [[0] * len(grid[0]) for i in range(len(grid))]
    val = helper(0,0,grid,dp)
    print dp
    return val

当你从网格边缘掉下来时,我认为返回0是不正确的。 这让你看起来已经成功了。 因此,我认为您错误报告的2是左上角的1​​加左下角的1,然后是“成功”从网格底部掉落。 我建议你调整你的返回逻辑,看起来像这样:

if at right or bottom edge:
  there is only one direction to go, so
  return the result of going in that direction
else you do have options, so
  return the minimum of the two choices, like you do now

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM