下降路径最小和
思路:
新建一个跟数组一样大的dp表,dp[i][j]表示经过A[i][j]点时最小的路径和。
class Solution(object):
def minFallingPathSum(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
m = len(A)
n = len(A[0])
dp = [[0] * n for _ in range(m)]
dp[0] = A[0]
for i in range(1, m):
for j in range(n):
if 0<=j-1<=n-1 and 0<=j+1<=n-1:
dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i-1][j+1]) + A[i][j]
elif 0<=j-1<=n-1:
dp[i][j] = min(dp[i-1][j], dp[i-1][j-1]) + A[i][j]
else:
dp[i][j] = min(dp[i-1][j], dp[i-1][j+1]) + A[i][j]
return min(dp[-1])