64. Minimum Path Sum
2018-04-24 本文已影响0人
liuhaohaohao
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.
Example:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
Solution
class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] map = new int[m][n];
if (m == 0 || n == 0) {return 0;}
map[0][0] = grid[0][0];
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
if (i == 0) {
if (j > 0){
map[i][j] = grid[i][j] + map[i][j-1];
}
}
else if (j == 0) {
if (i > 0){
map[i][j] = grid[i][j] + map[i-1][j];
}
}
else {
map[i][j] = Math.min(map[i-1][j], map[i][j-1]) + grid[i][j];
}
}
}
return map[m-1][n-1];
}
}