LeetCode 题解工作台

最小路径和

给定一个包含非负整数的 m x n 网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。 说明: 每次只能向下或者向右移动一步。 示例 1: 输入: grid = [[1,3,1],[1,5,1],[4,2,1]] 输出: 7 解释: 因为路径 1→3→1→1→1 的总和…

category

3

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们定义 表示从左上角走到 $(i, j)$ 位置的最小路径和。初始时 $f[0][0] = grid[0][0]$,答案为 $f[m - 1][n - 1]$。 考虑 :

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个包含非负整数的 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.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 200
lightbulb

解题思路

方法一:动态规划

我们定义 f[i][j]f[i][j] 表示从左上角走到 (i,j)(i, j) 位置的最小路径和。初始时 f[0][0]=grid[0][0]f[0][0] = grid[0][0],答案为 f[m1][n1]f[m - 1][n - 1]

考虑 f[i][j]f[i][j]

  • 如果 j=0j = 0,那么 f[i][j]=f[i1][j]+grid[i][j]f[i][j] = f[i - 1][j] + grid[i][j]
  • 如果 i=0i = 0,那么 f[i][j]=f[i][j1]+grid[i][j]f[i][j] = f[i][j - 1] + grid[i][j]
  • 如果 i>0i \gt 0j>0j \gt 0,那么 f[i][j]=min(f[i1][j],f[i][j1])+grid[i][j]f[i][j] = \min(f[i - 1][j], f[i][j - 1]) + grid[i][j]

最后返回 f[m1][n1]f[m - 1][n - 1] 即可。

时间复杂度 O(m×n)O(m \times n),空间复杂度 O(m×n)O(m \times n)。其中 mmnn 分别是网格的行数和列数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

最小路径和题解:状态·转移·动态规划 | LeetCode #64 中等