LeetCode 题解工作台

下降路径最小和 II

给你一个 n x n 整数矩阵 grid ,请你返回 非零偏移下降路径 数字和的最小值。 非零偏移下降路径 定义为:从 grid 数组中的每一行选择一个数字,且按顺序选出来的数字中,相邻数字不在原数组的同一列。 示例 1: 输入: grid = [[1,2,3],[4,5,6],[7,8,9]] 输…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

困难 · 状态·转移·动态规划

bolt

答案摘要

我们定义 表示前 行,且最后一个数字在第 列的最小数字和。那么状态转移方程为: $$

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 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].length
  • 1 <= n <= 200
  • -99 <= grid[i][j] <= 99
lightbulb

解题思路

方法一:动态规划

我们定义 f[i][j]f[i][j] 表示前 ii 行,且最后一个数字在第 jj 列的最小数字和。那么状态转移方程为:

f[i][j]=minkjf[i1][k]+grid[i1][j]f[i][j] = \min_{k \neq j} f[i - 1][k] + grid[i - 1][j]

其中 kk 表示第 i1i - 1 行的数字在第 kk 列,第 ii 行第 jj 列的数字为 grid[i1][j]grid[i - 1][j]

最后答案为 f[n]f[n] 中的最小值。

时间复杂度 O(n3)O(n^3),空间复杂度 O(n2)O(n^2)。其中 nn 为矩阵的行数。

我们注意到,状态 f[i][j]f[i][j] 只与 f[i1][k]f[i - 1][k] 有关,因此我们可以使用滚动数组优化空间复杂度,将空间复杂度优化到 O(n)O(n)

1
2
3
4
5
6
7
8
9
10
11
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)
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

下降路径最小和 II题解:状态·转移·动态规划 | LeetCode #1289 困难