一个m*n的表格,每个格子有一个非负数,求从左上到右下最短的路径值
和62,63两个值是同一个思路,建立dp表,记录每个位置到右下角的最短路径的值
1 class Solution(object): 2 def minPathSum(self, grid): 3 m,n = len(grid),len(grid[0]) 4 flag = [[0 for i in range(n)] for j in range(m)] 5 flag[m-1][n-1] = grid[m-1][n-1] 6 for i in range(m-1,-1,-1): 7 for j in range(n-1,-1,-1): 8 if i==m-1: 9 if j!=n-1: 10 flag[i][j] = grid[i][j] + flag[i][j+1] 11 elif j==n-1: 12 if i!=m-1: 13 flag[i][j] = grid[i][j] + flag[i+1][j] 14 else: 15 flag[i][j] = min(flag[i+1][j],flag[i][j+1])+grid[i][j] 16 return flag[0][0]
占用线性空间的解法:
1 class Solution(object):
2 def minPathSum(self, grid):
3 m,n = len(grid),len(grid[0])
4 flag = [0]+[sys.maxint]*(n-1)
5 for i in range(m):
6 flag[0] += grid[i][0]
7 for j in range(1,n):
8 flag[j] = min(flag[j],flag[j-1]) + grid[i][j]
9 return flag[-1]
10