动态规划。就是要注意第0行和第0列的初始化。
public class Solution { public int minPathSum(int[][] grid) { // Start typing your Java solution below // DO NOT write main() function int m = grid.length; if (m == 0) return 0; int n = grid[0].length; if (n == 0) return 0; int[][] mx = new int[m][n]; mx[0][0] = grid[0][0]; for (int i = 1; i < m; i++) { mx[i][0] = mx[i-1][0] + grid[i][0]; } for (int j = 1; j < n; j++) { mx[0][j] = mx[0][j-1] + grid[0][j]; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { mx[i][j] = Math.min(mx[i-1][j], mx[i][j-1]) + grid[i][j]; } } return mx[m-1][n-1]; } }
Python3
class Solution: def minPathSum(self, grid: List[List[int]]) -> int: if len(grid) == 0 or len(grid[0]) == 0: return 0 m = len(grid) n = len(grid[0]) memo = {} for i in range(m): for j in range(n): if i == 0 and j == 0: memo[(i, j)] = grid[i][j] elif i == 0: memo[(i, j)] = grid[i][j] + memo[(i, j - 1)] elif j == 0: memo[(i, j)] = grid[i][j] + memo[(i - 1, j)] else: # i != 0 or j != 0 memo[(i, j)] = grid[i][j] + min(memo[(i - 1, j)], memo[(i, j - 1)]) return memo[(m - 1, n - 1)]