-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path64_min_path_sum.py
More file actions
38 lines (30 loc) · 814 Bytes
/
Copy path64_min_path_sum.py
File metadata and controls
38 lines (30 loc) · 814 Bytes
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
38
from typing import List
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
dp = grid[0].copy()
for i in range(1, n):
dp[i] += dp[i - 1]
for i in range(1, m):
for j in range(0, n):
if j == 0:
dp[j] += grid[i][j]
else:
dp[j] = min(dp[j], dp[j - 1]) + grid[i][j]
return dp[-1]
def test():
tests = [
(
[
[1, 3, 1],
[1, 5, 1],
[4, 2, 1]
], 7
)
]
s = Solution()
for grid, target in tests:
ans = s.minPathSum(grid)
assert ans == target, f"except {target}, got {ans}"
if __name__ == "__main__":
test()