题目:
给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。 说明:每次只能向下或者向右移动一步。
思路:
本题较简单。
程序:
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
row = len(grid)
if row <= 0:
return 0
if row == 0 and column == 0:
return grid[0][0]
column = len(grid[0])
result = [[0] * (column) for _ in range(row)]
if row >= 1 and column >= 1:
result[0][0] = grid[0][0]
for index2 in range(1, column):
result[0][index2] = grid[0][index2 - 1] + grid[0][index2]
grid[0][index2] = result[0][index2]
for index1 in range(1, row):
result[index1][0] = grid[index1 - 1][0] + grid[index1][0]
grid[index1][0] = result[index1][0]
for index3 in range(1, row):
for index4 in range(1, column):
result[index3][index4] = min((result[index3 - 1][index4] + grid[index3][index4]),(result[index3][index4 - 1] + grid[index3][index4]))
return result[-1][-1]