友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

931. Minimum Falling Path Sum

Given a square array of integers A, we want the minimum sum of a falling path through A.

A falling path starts at any element in the first row, and chooses one element from each row. The next row’s choice must be in a column that is different from the previous row’s column by at most one.

Example 1:

Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: 12
Explanation:
The possible falling paths are:
  • [1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9]

  • [2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9]

  • [3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9]

The falling path with the smallest sum is [1,4,7], so the answer is 12.

Note:

  • 1 ⇐ A.length == A[0].length ⇐ 100

  • -100 ⇐ A[i][j] ⇐ 100

思路分析

  • 一刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * 动态规划,没有优化
 *
 * @author D瓜哥 · https://www.diguage.com
 * @since 2024-09-03 14:26:47
 */
public int minFallingPathSum(int[][] matrix) {
  int[][] dp = new int[matrix.length][matrix[0].length];
  System.arraycopy(matrix[0], 0, dp[0], 0, matrix[0].length);
  for (int row = 1; row < matrix.length; row++) {
    for (int column = 0; column < matrix[row].length; column++) {
      int num = dp[row - 1][column];
      if (0 <= column - 1) {
        num = Math.min(num, dp[row - 1][column - 1]);
      }
      if (column + 1 < matrix[row].length) {
        num = Math.min(num, dp[row - 1][column + 1]);
      }
      dp[row][column] = matrix[row][column] + num;
    }
  }
  int result = Integer.MAX_VALUE;
  for (int column = 0; column < dp[dp.length - 1].length; column++) {
    result = Math.min(result, dp[dp.length - 1][column]);
  }
  return result;
}