forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
minimum-path-sum.py
31 lines (27 loc) · 978 Bytes
/
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
from __future__ import print_function
# Time: O(m * n)
# Space: O(m + n)
#
# Given a m x n grid filled with non-negative numbers,
# find a path from top left to bottom right which minimizes the sum of all numbers along its path.
#
# Note: You can only move either down or right at any point in time.
#
class Solution:
# @param grid, a list of lists of integers
# @return an integer
def minPathSum(self, grid):
sum = list(grid[0])
for j in xrange(1, len(grid[0])):
sum[j] = sum[j - 1] + grid[0][j]
for i in xrange(1, len(grid)):
sum[0] += grid[i][0]
for j in xrange(1, len(grid[0])):
sum[j] = min(sum[j - 1], sum[j]) + grid[i][j]
return sum[-1]
if __name__ == "__main__":
print(Solution().minPathSum([[0,1]
,[1,0]]))
print(Solution().minPathSum([[1,3,1]
,[1,5,1]
,[4,2,1]]))