Minimum Path Sum
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.
Note: You can only move either down or right at any point in time.
先算每行第一个,和每列第一个,然后每一个dp里都是取前一个左边或者上边一个最小值加上当前值。返回[m-1][n-1]
1 public class Solution { 2 public int minPathSum(int[][] grid) { 3 if(grid ==null || grid.length==0 ||grid[0].length==0){ 4 return 0; 5 } 6 int m = grid.length; 7 int n = grid[0].length; 8 int[][] dp = new int[m][n]; 9 dp[0][0]= grid[0][0]; 10 11 for(int i = 1; i < m ; i++){ 12 dp[i][0] = dp[i-1][0]+grid[i][0]; 13 } 14 for(int j = 1; j < n ; j++){ 15 dp[0][j] = dp[0][j-1] + grid[0][j]; 16 } 17 18 for(int i = 1; i < m ; i++){ 19 for(int j = 1; j < n; j++){ 20 dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j]; 21 } 22 } 23 return dp[m-1][n-1]; 24 } 25 }