难度: Medium
原题连接
内容描述
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:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
思路 1 - 时间复杂度: O(N^2)- 空间复杂度: O(N^2)******
- 经典的动态规划问题,和:72. 编辑距离 类似
dp[i][j]代表到达点(i, j)所需要的最短路径和
beats 94.63%
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or len(grid) == 0:
return 0
row = len(grid)
col = len(grid[0]) if row else 0
dp = [[grid[i][j] for j in range(col)] for i in range(row)]
for i in range(1, col):
dp[0][i] += dp[0][i-1]
for i in range(1, row):
dp[i][0] += dp[i-1][0]
for i in range(1, row):
for j in range(1, col):
dp[i][j] += min(dp[i-1][j], dp[i][j-1])
return dp[-1][-1]
思路 2 - 时间复杂度: O(N^2)- 空间复杂度: O(1)******
其实我们根本不需要额外的空间
beats 94.63%
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or len(grid) == 0:
return 0
row = len(grid)
col = len(grid[0]) if row else 0
for i in range(1, col):
grid[0][i] += grid[0][i-1]
for i in range(1, row):
grid[i][0] += grid[i-1][0]
for i in range(1, row):
for j in range(1, col):
grid[i][j] += min(grid[i-1][j], grid[i][j-1])
return grid[-1][-1]