题目描述:
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]