-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathminimum-cost-path-with-alternating-directions-ii.py
More file actions
46 lines (43 loc) · 1.27 KB
/
minimum-cost-path-with-alternating-directions-ii.py
File metadata and controls
46 lines (43 loc) · 1.27 KB
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
# Time: O(m * n)
# Space: O(1)
# dp
class Solution(object):
def minCost(self, m, n, waitCost):
"""
:type m: int
:type n: int
:type waitCost: List[List[int]]
:rtype: int
"""
waitCost[0][0] = waitCost[m-1][n-1] = 0
for i in xrange(m):
for j in xrange(n):
prev = 0 if (i, j) == (0, 0) else float("inf")
if i-1 >= 0:
prev = min(prev, waitCost[i-1][j])
if j-1 >= 0:
prev = min(prev, waitCost[i][j-1])
waitCost[i][j] += prev+(i+1)*(j+1)
return waitCost[m-1][n-1]
# Time: O(m * n)
# Space: O(n)
# dp
class Solution2(object):
def minCost(self, m, n, waitCost):
"""
:type m: int
:type n: int
:type waitCost: List[List[int]]
:rtype: int
"""
waitCost[0][0] = waitCost[m-1][n-1] = 0
dp = [0]*n
for i in xrange(m):
for j in xrange(n):
prev = 0 if (i, j) == (0, 0) else float("inf")
if i-1 >= 0:
prev = min(prev, dp[j])
if j-1 >= 0:
prev = min(prev, dp[j-1])
dp[j] = prev+waitCost[i][j]+(i+1)*(j+1)
return dp[n-1]