https://leetcode-cn.com/problems/minimum-falling-path-sum/

原题

给你一个 n x n 的 方形 整数数组 matrix ,请你找出并返回通过 matrix 的下降路径 的 最小和 。

下降路径 可以从第一行中的任何元素开始,并从每一行中选择一个元素。在下一行选择的元素和当前行所选元素最多相隔一列(即位于正下方或者沿对角线向左或者向右的第一个元素)。具体来说,位置 (row, col) 的下一个元素应当是 (row + 1, col - 1)、(row + 1, col) 或者 (row + 1, col + 1) 。

示例 1:
输入:matrix = [[2,1,3],[6,5,4],[7,8,9]]
输出:13
解释:下面是两条和最小的下降路径,用加粗标注:
[[2,1,3], [[2,1,3],
[6,5,4], [6,5,4],
[7,8,9]] [7,8,9]]

示例 2:
输入:matrix = [[-19,57],[-40,-5]]
输出:-59
解释:下面是一条和最小的下降路径,用加粗标注:
[[-19,57],
[-40,-5]]

示例 3:
输入:matrix = [[-48]]
输出:-48

提示:
n == matrix.length
n == matrix[i].length
1 <= n <= 100
-100 <= matrix[i][j] <= 100

题目分析

又是求最小值,先穷举,再优化。
image.png
可以看出我们求 matrix[0, 0] 到达底部的最小值为 2 + min(matrix[1, 0], matrix[1, 1]),求 matrix[0, 1] 到达底部的最小值为 1 + min(matrix[1, 0], matrix[1, 1], matrix[1, 2])。
因此可以写出递归函数为,使用 cache 来保存每一步子问题的结果:

  1. const minFallingPathSum = (matrix) => {
  2. const rows = matrix.length
  3. const cols = matrix[0].length
  4. const cache = new Array(rows)
  5. const dp = (i, j) => {
  6. // 如果 j 已经到达最后一层,说明递归可以结束了
  7. if (i >= rows) return 0
  8. // 边界问题退出
  9. if (j < 0 || j >= cols) return Number.MAX_SAFE_INTEGER
  10. if (!cache[i]) cache[i] = []
  11. if (cache[i][j]) return cache[i][j]
  12. const leftBottom = dp(i + 1, j - 1)
  13. const bottom = dp(i + 1, j)
  14. const rightBottom = dp(i + 1, j + 1)
  15. cache[i][j] = matrix[i][j] + Math.min.apply(null, [leftBottom, bottom, rightBottom])
  16. return cache[i][j]
  17. }
  18. const pathSum = []
  19. for (let i = 0; i < cols; i++) {
  20. pathSum[i] = dp(0, i)
  21. }
  22. return Math.min(...pathSum)
  23. }

时间复杂度为 o(n ^ 2),空间复杂度为 o(n ^ 2)
知道了递归自上而下的过程是为了求出 cache 数组,因此我们可以先求出 cache,直接返回 cache[0] 中的最小值。

  1. const minFallingPathSum = (matrix) => {
  2. const cache = []
  3. const rows = matrix.length
  4. const cols = matrix[0].length
  5. for (let i = rows - 1; i >= 0; i--) {
  6. if (!cache[i]) cache[i] = []
  7. for (let j = 0; j < cols; j++) {
  8. if (i === rows - 1) {
  9. cache[i][j] = matrix[i][j]
  10. } else {
  11. const leftBottom = j - 1 < 0 ? Number.MAX_SAFE_INTEGER : cache[i + 1][j - 1]
  12. const bottom = cache[i + 1][j]
  13. const rightBottom = j + 1 >= cols ? Number.MAX_SAFE_INTEGER : cache[i + 1][j + 1]
  14. cache[i][j] = matrix[i][j] + Math.min(...[leftBottom, bottom, rightBottom])
  15. }
  16. }
  17. }
  18. return Math.min(...cache[0])
  19. }

时间复杂度为 o(n ^ 2),空间复杂度为 o(n ^ 2)