您的位置:首页 > 编程语言 > Python开发

LeetCode 64. Minimum Path Sum(Python)

2017-08-19 15:19 483 查看
题目描述:

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.

思路:

本题求左上角到右下角的最短路径,因为只允许向下或向右操作,所以该问题可以化简为(i, j)处(i > 0, j > 0)的最短路径就是(i - 1, j)和(i, j - 1)处的较小值加上(i, j)的value

AC代码:

class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
res = [[0 for i in range(len(grid[0]))] for i in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
if i == 0:
res[i][j] = res[i][j - 1] + grid[i][j]
elif j == 0:
res[i][j] = res[i - 1][j] + grid[i][j]
else:
res[i][j] = min(res[i - 1][j], res[i][j - 1]) + grid[i][j]
return res[-1][-1]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: