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.
标准的Dynamic Programming。注意第一行的元素只能从左边走过来,第一列的只能从上边走下来。
public class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] result = new int[m][n];
//fill the first row of result, i.e. result[0]
int sum = 0;
for(int i = 0; i < n; i++){
sum += grid[0][i];
result[0][i] = sum;
}
//fill the first column
sum = 0;
for(int j = 0; j < m; j++){
sum += grid[j][0];
result[j][0] = sum;
}
//fill the rest
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
result[i][j] = Math.min(result[i - 1][j], result[i][j - 1]) + grid[i][j];
}
}
return result[m - 1][n - 1];
}
}