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.
Link: 点击打开链接
思路 :动态规划, f[i][j] = Min(f[i - 1][j], f[i][j - 1]) + a[i][j];
public class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] aux = new int[m][n];
aux[0][0] = grid[0][0];
//find the minimum path to the left side
for(int i = 0; i < m - 1; i++){
aux[i + 1][0] = aux[i][0] + grid[i + 1][0];
}
//find the minimum path to the top side
for(int j = 0; j < n - 1; j++){
aux[0][j + 1] = aux[0][j] + grid[0][j + 1];
}
for(int i = 0; i < m - 1; i++){
for(int j = 0; j < n - 1; j++){
aux[i + 1][j + 1] = Math.min(aux[i + 1][j], aux[i][j + 1]) + grid[i + 1][j + 1];
}
}
return aux[m - 1][n - 1];
}
}