64. Minimum Path Sum

初看以为是BFS(爬格子),细品发现是DP题(find minimum),因为只考虑往下和往右走,简单了很多,可以借助hashmap(v1),也可以直接 bottom-up DP。

如果 follow-up 变成可以往左和往上走,情况会复杂不少(不记录path的话会绕圈圈),heap会是个更好的选择。

class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        dp = dict()
        dp[(0, 0)] = grid[0][0]
        
        def backSearch(y, x):
            if (y, x) in dp: 
                return dp[(y, x)]
            prev = [backSearch(a, b) for (a, b) in [(y, x-1), (y-1, x)] if 0<=a<m and 0<=b<n]
            dp[(y, x)] = grid[y][x] + min(prev)
            return dp[(y, x)]
        
        return backSearch(m-1, n-1)

Last updated

Was this helpful?