LeetCode 题解工作台
下降路径最小和 II
给你一个 n x n 整数矩阵 grid ,请你返回 非零偏移下降路径 数字和的最小值。 非零偏移下降路径 定义为:从 grid 数组中的每一行选择一个数字,且按顺序选出来的数字中,相邻数字不在原数组的同一列。 示例 1: 输入: grid = [[1,2,3],[4,5,6],[7,8,9]] 输…
3
题型
6
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们定义 表示前 行,且最后一个数字在第 列的最小数字和。那么状态转移方程为: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个 n x n 整数矩阵 grid ,请你返回 非零偏移下降路径 数字和的最小值。
非零偏移下降路径 定义为:从 grid 数组中的每一行选择一个数字,且按顺序选出来的数字中,相邻数字不在原数组的同一列。
示例 1:

输入:grid = [[1,2,3],[4,5,6],[7,8,9]] 输出:13 解释: 所有非零偏移下降路径包括: [1,5,9], [1,5,7], [1,6,7], [1,6,8], [2,4,8], [2,4,9], [2,6,7], [2,6,8], [3,4,8], [3,4,9], [3,5,7], [3,5,9] 下降路径中数字和最小的是 [1,5,7] ,所以答案是 13 。
示例 2:
输入:grid = [[7]] 输出:7
提示:
n == grid.length == grid[i].length1 <= n <= 200-99 <= grid[i][j] <= 99
解题思路
方法一:动态规划
我们定义 表示前 行,且最后一个数字在第 列的最小数字和。那么状态转移方程为:
其中 表示第 行的数字在第 列,第 行第 列的数字为 。
最后答案为 中的最小值。
时间复杂度 ,空间复杂度 。其中 为矩阵的行数。
我们注意到,状态 只与 有关,因此我们可以使用滚动数组优化空间复杂度,将空间复杂度优化到 。
class Solution:
def minFallingPathSum(self, grid: List[List[int]]) -> int:
n = len(grid)
f = [0] * n
for row in grid:
g = row[:]
for i in range(n):
g[i] += min((f[j] for j in range(n) if j != i), default=0)
f = g
return min(f)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N^2) because each cell requires scanning N previous elements, optimized by tracking smallest and second smallest values. Space can be reduced to O(N) by reusing row arrays instead of a full DP matrix. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Are you enforcing the non-zero column shift in your state transitions?
- question_mark
Can you optimize your DP to reduce space while maintaining correctness?
- question_mark
How do you handle ties for minimum values when skipping the same column?
常见陷阱
外企场景- error
Forgetting to exclude the same column in consecutive rows, leading to invalid paths.
- error
Using full N x N DP without optimization, causing unnecessary space usage.
- error
Incorrectly updating the minimum when multiple columns share the smallest value.
进阶变体
外企场景- arrow_right_alt
Allow negative and positive values, increasing the risk of selecting suboptimal paths.
- arrow_right_alt
Compute the maximum falling path sum instead of minimum, applying the same DP logic.
- arrow_right_alt
Handle non-square matrices where row and column counts differ, requiring adjusted state tracking.