基础动态规划
base case:
dp[0][i] = matrix[0][i]
状态转移记住有三个方向还有注意不要越界
def minFallingPathSum(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
m,n = len(matrix),len(matrix[0])
dp = [[22222]*n for i in range(m)]
for i in range(n):
dp[0][i] = matrix[0][i]
for i in range(1,m):
for j in range(0,n):
if j-1 >= 0 and j+1 < n:
dp[i][j] = min(dp[i-1][j],dp[i-1][j-1],dp[i-1][j+1]) + matrix[i][j]
elif j-1 < 0:
dp[i][j] = min(dp[i-1][j],dp[i-1][j+1]) + matrix[i][j]
else:
dp[i][j] = min(dp[i-1][j],dp[i-1][j-1]) + matrix[i][j]
return min(dp[-1])