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.
Java Solutions:
1. DP, O(n^2) time, O(n^2) space
public class Solution {
public int minPathSum(int[][] grid) {
if(grid==null||grid.length==0)
return 0;
int row=grid.length;
int column=grid[0].length;
int[][] results=new int[row][column];
results[0][0]=grid[0][0];
//count the first row
for(int i=1;i<row;i++)
results[i][0]=grid[i][0]+results[i-1][0];
//count the first column
for(int j=1;j<column;j++)
results[0][j]=grid[0][j]+results[0][j-1];
for(int i=1;i<row;i++)
for(int j=1;j<column;j++){
results[i][j]=grid[i][j]+Math.min(results[i-1][j],results[i][j-1]);
}
return results[row-1][column-1];
}
}
2.DP, O(n^2) time, O(n) space
public class Solution {
public int minPathSum(int[][] grid) {
if(grid==null||grid.length==0)
return 0;
int row=grid.length;
int column=grid[0].length;
int[] results=new int[column];
//init
Arrays.fill(results,Integer.MAX_VALUE);
results[0]=0;
for(int i=0;i<row;i++){
//init the 0th sum = old 0th element + the new 0th element
//just init the 0th column every time dynamically
results[0]=grid[i][0]+results[0];
loop through each element of each row
for(int j=1;j<column;j++){
results[j]=grid[i][j]+Math.min(results[j],results[j-1];
}
}
return results[column-1];
}
}