Link: https://oj.leetcode.com/problems/minimum-path-sum/
My thought: Simple 2d-DP. I passed OJ on my first attempt.
Approach I : Time: O(mn), Space: O(1)
public class Solution {
//my 1st attempt: g[i][j] = min(g[i-1][j], g[i][j-1]) + g[i][j]
public int minPathSum(int[][] grid) {
if(grid == null) return 0;
//init the 1st row
for(int j = 1; j < grid[0].length; j++){
grid[0][j] += grid[0][j-1];
}
//init the 1st col
for(int i = 1; i < grid.length; i++){
grid[i][0] += grid[i-1][0];
}
for(int i = 1; i < grid.length; i++){
for(int j = 1; j < grid[0].length; j++){
grid[i][j] += Math.min(grid[i-1][j], grid[i][j-1]);
}
}
return grid[grid.length-1][grid[0].length-1];
}
}
Approach II: DP with 滚动数组
Time: O(mn), Space: O(n)
public class Solution {
//my 2nd attempt
public int minPathSum(int[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) return 0;
int[] res = new int[grid[0].length];
//init the 1st row: i = 0
res[0] = grid[0][0];
for(int j = 1; j < grid[0].length; j++){
res[j] = res[j-1] + grid[0][j];
}
for(int i = 1; i < grid.length; i++){
res[0] += grid[i][0];
for(int j = 1; j < grid[0].length; j++){
res[j] = Math.min(res[j], res[j-1]) + grid[i][j];
}
}
return res[grid[0].length-1];
}
}
相关题目: 10.2 Unique Paths, 10.3 Unique Paths II