leetcode-1289-Minimum Falling Path Sum II
问题
Given a square grid of integers arr
, a falling path with non-zero shifts is a choice of exactly one element from each row of arr
, such that no two elements chosen in adjacent rows are in the same column.
Return the minimum sum of a falling path with non-zero shifts.
Example 1:
1 | Input: arr = [[1,2,3],[4,5,6],[7,8,9]] |
Constraints:
1 <= arr.length == arr[i].length <= 200
-99 <= arr[i][j] <= 99
分析
思路1: $dp[i][j]$ 表示从第 $0$ 行到第 $i$ 行,最后停止在位置 $j$ 上的最短路径。每次找到最小的 $dp[i-1][k] \; (k \neq j)$ 然后加上 $arr[i][j]$ 即可。时间复杂度 $O(n^3)$
思路2: 虽短时间复杂度。针对上一行寻找最小值的情况,我们可以记录上一行的最小值 $fm$ ,上一行的次小值 $sm$ ,以及上一行最小值的下标 $k$ ,对于 $dp[i][j] $ ,$j \neq k$ 时,使用 $fm + arr[i][j]$ ,当 $j == k$ 时,使用 $sm + arr[i][j]$ 。处理完一行的同时更新 $fm, sm, k$。时间复杂度为 $O(n^2)$。
代码1
1 | // O(n^3) |
代码2
1 | // O(n^2) |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/30/leetcode-1289/
License: 知识共享署名-非商业性使用 4.0 国际许可协议