64. Minimum Path Sum

weixin_34236869發表於2018-05-03

這一題依然是很簡單的動態規劃題目:

class Solution(object):
    def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        m = len(grid)
        n = len(grid[0])
        if m == 0:
            return 0
        if m == 1 and n == 1:
            return grid[0][0]
        if m == 1:
            s = 0
            for i in range(n):
                s += grid[0][i]
            return s
        if n == 1:
            s = 0
            for i in range(m):
                s += grid[i][0]
            return s
        dp = [[0 for i in range(n)] for j in range(m)]
        dp[0][0] = grid[m-1][n-1]
        for i in range(1,m):
            dp[i][0] = grid[m-1-i][n-1] + dp[i-1][0]
        for i in range(1,n):
            dp[0][i] = grid[m-1][n-1-i] + dp[0][i-1]
        for i in range(1,m):
            for j in range(1,n):
                dp[i][j] = grid[m-1-i][n-1-j] + min(dp[i-1][j], dp[i][j-1])
        return dp[m-1][n-1]

相關文章