题目:
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.
1 public class Solution { 2 public int minPathSum(int[][] grid) 3 { 4 int m = grid.length; 5 int n = grid[0].length; 6 int[][] sum = new int [m][n]; 7 8 sum[0][0]=grid[0][0]; 9 for(int i=1;i<m;i++) 10 { 11 sum[i][0]=sum[i-1][0]+grid[i][0]; 12 } 13 14 for(int j=1;j<n;j++) 15 { 16 sum[0][j]=sum[0][j-1]+grid[0][j]; 17 } 18 19 for(int i=1;i<m;i++) 20 for(int j =1;j<n;j++) 21 { 22 sum[i][j]=Math.min(sum[i-1][j],sum[i][j-1])+grid[i][j]; 23 } 24 25 26 return sum[m-1][n-1]; 27 28 } 29 }
reference: http://www.jiuzhang.com/solutions/minimum-path-sum/