動態規劃 最小路徑和
給定一個只含非負整數的m*n網格,找到一條從左上角到右下角的可以使數字和最小的路徑。
只能向下走或者向右走
class Solution:
"""
@param grid: a list of lists of integers
@return: An integer, minimizes the sum of all numbers along its path
"""
def minPathSum(self, grid):
# write your code here
m = len(grid)
n = len(grid[0])
dp = [[0 for i in range(n)] for j in range(m)]
if grid[0][0] is None:
return None
elif m==0:
return None
dp[0][0] = grid[0][0]
"""
考慮邊界問題
"""
for i in range(m):
dp[i][0] = dp[i-1][0]+grid[i][0]
for j in range(n):
dp[0][j] = dp[0][j-1]+grid[0][j]
"""
一般情況
"""
for i in range(1,m):
for j in range(1,n):
dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i][j]
return dp[m-1][n-1]