矩阵

时间:2016-09-07 05:04:00

标签: python algorithm dynamic

问题 -

给定m x n网格填充非负数,找到从左上角到右下角的路径,这样可以最小化路径上所有数字的总和。

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

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

显示输出错误。

示例 -

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

1 个答案:

答案 0 :(得分:2)

当你从网格的边缘掉下来时,我不认为返回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
相关问题