一、题目描述
给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。说明:每次只能向下或者向右移动一步。
示例:
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。
二、代码实现
方法一:二维状态转移方程
dp[i][j] = Min( dp[i - 1][j] ,dp[i][j - 1] ) + grid[i][j]
空间复杂度 O(m x n)
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m, n = len(grid), len(grid[0])
if n == 0: return 0
dp = [[0] * n] * m
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = grid[i][j]
elif i == 0:
dp[i][j] = grid[i][j] + dp[i][j-1]
elif j == 0:
dp[i][j] = grid[i][j] + dp[i-1][j]
else:
dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1])
return dp[m-1][n-1]
方法二:状态压缩,一维状态转移方程
上面的方法中,时间复杂度为 O(nm), 但是辅助空间也为 O(nm)。通过压缩空间的方法来减小辅助空间,使得辅助空间只需要 O(m)。
状态转移方程:dp[ i ] = min ( dp[ i - 1] , dp[ i ] ) + grid[ i ] [ j ]
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m, n = len(grid), len(grid[0])
if n == 0: return 0
dp = [0] * n
dp[0] = grid[0][0]
for i in range(1, n):
dp[i] = dp[i-1] + grid[0][i]
for i in range(1, m):
for j in range(n):
if j == 0:
dp[j] = dp[j] + grid[i][j]
else:
dp[j] = min(dp[j-1], dp[j]) + grid[i][j]
return dp[n-1]
网友评论