LeetCode 64.最小路径和 Python解答

分析:

到达(m,n)有两种方式1.从(m-1,n)2.从(m,n-1)
f(m,n)为从(0,0)到(m,n)所需的最小路径和。
f(m,n)=min(f(m-1,n), f(m,n-1))+grid(m,n)

class Solution(object):
    def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        m = len(grid) # 行数
        n = len(grid[0]) # 列数
        # V1
        # def func(m,n):
        #     if n==0 and m>0:
        #         return func(m-1, 0) + grid[m][0]
        #     if m==0 and n>0:
        #         return func(0, n-1) + grid[0][n]
        #     if m==n==0:
        #         return grid[0][0]
        #     up = func(m - 1, n) + grid[m][n]
        #     left = func(m, n - 1) + grid[m][n]
        #     mn = min(up, left)
        #     return mn
        #
        #

        # return func(m-1, n-1)

        # V2
        res = [[0]*n for _ in range(m)] # 初始化全0矩阵
        res[0] = [sum(grid[0][:i+1]) for i in range(n)] # 计算出第0行
        temp = list(zip(*grid))[0] # 矩阵的转置,取出第0行
        for i in range(m):
            res[i][0] = sum(temp[:i+1]) # 计算出第0列
        for i in range(1, m):
            for j in range(1, n):
                res[i][j] = min(res[i-1][j], res[i][j-1])+grid[i][j] # 自下而上的递推赋值
        return res[-1][-1]

你可能感兴趣的:(LeetCode)