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.
采用动态规划的方法
每一个格子拥有的值是它左边的格子拥有的值和它上边的格子拥有的值的较小者加上格子自身的值;
而最左边和最上边的一排,每一个格子拥有的值是它左边(上边)相邻格子的值加上自己的值;
public class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int [][]a = new int[m][n];
a[0][0] = grid[0][0];
for(int i = 1;i < m;i++) a[i][0]= grid[i][0]+a[i-1][0] ;
for(int i = 1;i < n;i++) a[0][i] = grid[0][i]+a[0][i-1];
for(int i = 1;i < m;i++){
for(int j = 1;j < n;j++){
a[i][j] =(int)Math.min(a[i-1][j],a[i][j-1])+grid[i][j];
}
}
return a[m-1][n-1];
}
}