-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC0232.py
38 lines (24 loc) · 990 Bytes
/
LC0232.py
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
29
30
31
32
33
34
35
36
37
class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
m, n = len(A), len(A[0])
if m == 1 or n == 1:
return A[0][0]
dp = [[float('inf')] * n for _ in range(m)]
ans = float('inf')
for i in range(len(A)):
ans = min(ans, self.minFallingPathSumHelper(A, 0, i, dp))
return ans
def minFallingPathSumHelper(self, A, row, col, dp):
m, n = len(A), len(A[0])
if dp[row][col] != float('inf'):
return dp[row][col]
if row == m - 1:
return A[row][col]
left = right = float('inf')
if col > 0:
left = self.minFallingPathSumHelper(A, row + 1, col - 1, dp)
straight = self.minFallingPathSumHelper(A, row + 1, col, dp)
if col < n - 1:
right = self.minFallingPathSumHelper(A, row + 1, col + 1, dp)
dp[row][col] = min(left, min(straight, right)) + A[row][col]
return dp[row][col]