LeetCode 题解工作台
最小路径和
给定一个包含非负整数的 m x n 网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。 说明: 每次只能向下或者向右移动一步。 示例 1: 输入: grid = [[1,3,1],[1,5,1],[4,2,1]] 输出: 7 解释: 因为路径 1→3→1→1→1 的总和…
3
题型
8
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示从左上角走到 $(i, j)$ 位置的最小路径和。初始时 $f[0][0] = grid[0][0]$,答案为 $f[m - 1][n - 1]$。 考虑 :
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给定一个包含非负整数的 m x n 网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
说明:每次只能向下或者向右移动一步。
示例 1:
输入:grid = [[1,3,1],[1,5,1],[4,2,1]] 输出:7 解释:因为路径 1→3→1→1→1 的总和最小。
示例 2:
输入:grid = [[1,2,3],[4,5,6]] 输出:12
提示:
m == grid.lengthn == grid[i].length1 <= m, n <= 2000 <= grid[i][j] <= 200
解题思路
方法一:动态规划
我们定义 表示从左上角走到 位置的最小路径和。初始时 ,答案为 。
考虑 :
- 如果 ,那么 ;
- 如果 ,那么 ;
- 如果 且 ,那么 。
最后返回 即可。
时间复杂度 ,空间复杂度 。其中 和 分别是网格的行数和列数。
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
f = [[0] * n for _ in range(m)]
f[0][0] = grid[0][0]
for i in range(1, m):
f[i][0] = f[i - 1][0] + grid[i][0]
for j in range(1, n):
f[0][j] = f[0][j - 1] + grid[0][j]
for i in range(1, m):
for j in range(1, n):
f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j]
return f[-1][-1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you understand how each cell's minimum sum depends on its top and left neighbors?
- question_mark
Can you optimize the space usage while maintaining correct DP transitions?
- question_mark
Will you correctly handle edge cases like the first row and first column for accurate sums?
常见陷阱
外企场景- error
Failing to correctly initialize the first row or first column, leading to incorrect path sums.
- error
Confusing the direction of allowed moves and attempting diagonal or upward transitions.
- error
Using recursive solutions without memoization, causing time limit exceeded errors on large grids.
进阶变体
外企场景- arrow_right_alt
Minimum Path Sum II with obstacles blocking certain cells.
- arrow_right_alt
Maximum Path Sum on a grid with the same movement constraints.
- arrow_right_alt
Minimum Falling Path Sum allowing diagonal moves in addition to down and right.