Leetcode 931 Minimum Falling Path Sum

给定一个正方形矩阵A,求A中的最小下坠路径和!
一个下坠路径是指从第一行的任意一个位置开始,依次往下一行走,但相邻两行的列之差必须小于等于1!

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. 1 <= A.length == A[0].length <= 100
  2. -100 <= A[i][j] <= 100

题意分析:
典型的dp问题,leetcode之前有一道差不多的,那道题里面是说的树,这里是矩阵,差不多一个意思!

思路分析:
我们从下至上分析,定义dp[i][j]表示从(i,j)这个点出发,达到最底层的最小代价。
显然,我们所求的答案就是min(dp[0])。
那么有dp[i][j] = A[i][j] + min(dp[i+1][j-1],dp[i+1][j], dp[i+1][j+1])

初始化最后一行,dp[n-1] = A[n-1]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 36ms
class Solution(object):
def minFallingPathSum(self, A):
n = len(A)
dp = [[0]*n for _ in range(n)]
# 初始化
for j in range(n):
dp[n-1][j] = A[n-1][j]
# 懒得用技巧缩短代码了,这种测试直接写才是最快的
for i in range(n-2,-1,-1):
for j in range(n):
if j == 0:
dp[i][j] = A[i][j] + min(dp[i+1][j], dp[i+1][j+1])
elif j == n-1:
dp[i][j] = A[i][j] + min(dp[i+1][j-1], dp[i+1][j])
else:
dp[i][j] = A[i][j] + min(dp[i+1][j-1], dp[i+1][j], dp[i+1][j+1])
return min(dp[0])