mq059.最小路径和

 

题目链接

一个二维的dp,很熟练了。这个算法的时间复杂度是O(NM),空间复杂度是O(NM)。

python:

class Solution:
    def minPathSum(self, grid: List[List[int]]):
        lrow, lcol = len(grid), len(grid[0])

        for i in range(1, lrow):
            grid[i][0] += grid[i-1][0]
        for j in range(1, lcol):
            grid[0][j] += grid[0][j-1]
        
        print(grid)
        for i in range(1, lrow):
            for j in range(1, lcol):
                grid[i][j] += min(grid[i][j-1], grid[i-1][j])

        return grid[-1][-1]