首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

leetcode: 64. Minimum Path Sum

Problem

代码语言:javascript
复制
# Given a m x n grid filled with non-negative numbers,
# find a path from top left to bottom right 
# which minimizes the sum of all numbers along its path.
#
# Note: You can only move either down or right at any point in time.
#
# Example 1:
# [[1,3,1],
#  [1,5,1],
#  [4,2,1]]
#
# Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.

AC

代码语言:javascript
复制
class Solution():
    def minPathSum(self, x):
        m, n = len(x[0]), len(x)
        way = [0] * m
        way[0] = x[0][0]
        for j in range(1, m):
            way[j] = way[j-1] + x[0][j]
        for i in range(1, n):
            way[0] += x[i][0]
            for j in range(1, m):
                way[j] = min(way[j-1], way[j]) + x[i][j]
        return way[-1]


if __name__ == "__main__":
    assert Solution().minPathSum([[0,1], [1,0]]) == 1
    assert Solution().minPathSum([[1,3,1], [1,5,1], [4,2,1]]) == 7
下一篇
举报
领券