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.
Success
Runtime: 2 ms, faster than 90.95% of Java online submissions for Minimum Path Sum.
Memory Usage: 41.9 MB, less than 87.84% of Java online submissions for Minimum Path Sum.
class Solution {
public int minPathSum(int[][] grid) {
int l=grid.length;
int h=grid[0].length;
int[][] mingrid=new int[l][h];
mingrid[0][0]=grid[0][0];
for(int i=1;i<l;i++){
mingrid[i][0]=grid[i][0]+mingrid[i-1][0];
}
for(int i=1;i<h;i++){
mingrid[0][i]=grid[0][i]+mingrid[0][i-1];
}
for(int i=1;i<l;i++){
for(int j=1;j<h;j++){
mingrid[i][j]=Math.min(mingrid[i-1][j],mingrid[i][j-1])+grid[i][j];
}
}
return mingrid[l-1][h-1];
}
}