64. Minimum Path Sum
https://leetcode.com/problems/minimum-path-sum/description/
Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum.
Thoughts
Code
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
M = len(grid)
if M == 0:
return 0
N = len(grid[0])
dp = [0] * N
dp[0] = grid[0][0]
for j in range(1, N):
dp[j] = dp[j - 1] + grid[0][j]
for i in range(1, M):
dp[0] += grid[i][0]
for j in range(1, N):
dp[j] = min(dp[j], dp[j - 1]) + grid[i][j]
return dp[N - 1]Last updated