【leetcode】最小路径和(动态规划)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36372879/article/details/88645007

在这里插入图片描述


算法思想

不需要再使用函数了,直接初始化一个数组就行,使用一个二重循环。
遍历一遍,如果i和j都是0,那么直接初始化,否则按照路径初始化

class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        if grid == []:
            return 0
        rows, cols = len(grid), len(grid[0])
        memory = [([0] * cols) for i in range(rows)]
        for i in range(rows):
            for j in range(cols):
                if i - 1 >= 0 and j - 1 >= 0:
                    memory[i][j] = min(memory[i - 1][j], memory[i][j - 1]) + grid[i][j]
                elif i - 1 >= 0:
                    memory[i][j] = memory[i - 1][j] + grid[i][j]
                elif j - 1 >= 0:
                    memory[i][j] = memory[i][j - 1] + grid[i][j]
                else:
                    memory[i][j] = grid[i][j]
        return memory[rows - 1][cols - 1]

猜你喜欢

转载自blog.csdn.net/weixin_36372879/article/details/88645007