LeetCode 64. Minimum Path Sum

题目

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
2
3
4
5
6
7
8
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.

思路

DP.
新的一个点的最短路径一定等于其上方、左方最短路径+当前的值,
即有:grid[i][j] = min(grid[i-1][j], grid[i][j-1]) + grid[i][j]
同时注意i=0和j=0时的边界。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
tmp = 0
if i == 0 and j != 0:
tmp = grid[i][j-1]
if i != 0 and j == 0:
tmp = grid[i-1][j]
if i != 0 and j != 0:
tmp = min(grid[i-1][j], grid[i][j-1])
grid[i][j] = tmp + grid[i][j]
return grid[m-1][n-1]