-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path64.minimum-path-sum.py
63 lines (47 loc) · 1.43 KB
/
64.minimum-path-sum.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# Level: Medium
# TAGS: Array, Matrix, Dynamic Programming
from typing import List
class Solution:
# Bottom - Up
def minPathSum(self, grid: List[List[int]]) -> int:
n = len(grid)
m = len(grid[0])
dp = [[0] * m for _ in range(n)]
dp[0][0] = grid[0][0]
for i in range(1, m):
dp[0][i] = dp[0][i - 1] + grid[0][i]
for i in range(1, n):
dp[i][0] = dp[i - 1][0] + grid[i][0]
for i in range(1, n):
for j in range(1, m):
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
return dp[n - 1][m - 1]
# Top - Down
def minPathSumTopDown(self, grid: List[List[int]]) -> int:
n = len(grid)
m = len(grid[0])
memo = {}
def pathSum(i, j):
if i < 0 or j < 0:
return float("inf")
if (i, j) in memo:
return memo[(i, j)]
if i == 0 and j == 0:
return grid[0][0]
min_path = min(pathSum(i - 1, j), pathSum(i, j - 1)) + grid[i][j]
memo[(i, j)] = min_path
return min_path
return pathSum(n - 1, m - 1)
# solution = Solution().minPathSum
# print("7", solution([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))
# print("12", solution([[1, 2, 3], [4, 5, 6]]))
tests = [
(
([[1, 3, 1], [1, 5, 1], [4, 2, 1]],),
7,
),
(
([[1, 2, 3], [4, 5, 6]],),
12,
),
]