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. It can only move either down or right at any point in time.
Using dynamic programming to solve:
{ s u m ( i , j ) = s u m ( i − 1 , j ) + n o d e ( i , j ) i f s u m ( i − 1 , j ) ≤ s u m ( i , j − 1 ) s u m ( i , j ) = s u m ( i , j − 1 ) + n o d e ( i , j ) i f s u m ( i − 1 , j ) > s u m ( i , j − 1 ) \begin{cases} sum(i, j) = sum(i-1, j) + node(i, j) & if & sum(i-1, j) \le sum(i, j-1)\\ sum(i, j) = sum(i, j-1) + node(i, j) & if & sum(i-1, j) > sum(i, j-1)\\ \end{cases} {sum(i,j)=sum(i−1,j)+node(i,j)sum(i,j)=sum(i,j−1)+node(i,j)ififsum(i−1,j)≤sum(i,j−1)sum(i−1,j)>sum(i,j−1)
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
if not grid:
return 0
row = len(grid)
if not row:
return 0
col = len(grid[0])
if not col:
return 0
step = [[0] * col for _ in range(row)]
step[0][0] = grid[0][0]
for i in range(row):
for j in range(col):
flag = False
if i and flag == False:
step[i][j] = step[i-1][j] + grid[i][j]
flag = True
if j and (flag == False or step[i][j] > step[i][j-1] + grid[i][j]):
step[i][j] = step[i][j-1] + grid[i][j]
return step[row-1][col-1]