64. Minimum Path Sum
class Solution {
public int minPathSum(int[][] grid) {
int[] memo = new int[grid[0].length];
for(int i=0; i<grid.length;i++){
for (int j=0; j<grid[0].length; j++){
if(i == 0){
// important! initialize the first row
memo[j]=j==0? grid[0][0] : grid[i][j]+memo[j-1];
}
else if(j == 0){
memo[j]=memo[j]+grid[i][j];
}else{
// if first row does not get initialized, memo[j] is always 0;
memo[j] = grid[i][j]+Math.min(memo[j], memo[j-1]);
}
}
}
return memo[memo.length-1];
}
}
Last updated
Was this helpful?