路飞
⏰ 时间复杂度: O ( n m ) O(nm) O(nm)
空间复杂度: O ( n m ) O(nm) O(nm)
class Solution {
public int minPathSum(int[][] grid)
{
int n = grid.length;
if (n == 0)
return 0;
int m = grid[0].length;
int[][] f = new int[n][m];
f[0][0] = grid[0][0];
for (int i = 1; i < m; i++)
f[0][i] = f[0][i - 1] + grid[0][i];
for (int i = 1; i < n; i++)
f[i][0] = f[i - 1][0] + grid[i][0];
for (int i = 1; i < n; i++)
for (int j = 1; j < m; j++)
f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + grid[i][j];
return f[n - 1][m - 1];
}
}
⏰ 时间复杂度: O ( n m ) O(nm) O(nm)
空间复杂度: O ( 1 ) O(1) O(1)
class Solution {
public int minPathSum(int[][] grid) {
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
if(i == 0 && j == 0) continue;//不处理
else if(i == 0) grid[i][j] = grid[i][j - 1] + grid[i][j];//第一行的,只能从左边过来
else if(j == 0) grid[i][j] = grid[i - 1][j] + grid[i][j];//第一列的,只能从上面过来
else grid[i][j] = Math.min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j];//从上面或者左边较小的地方过来
}
}
return grid[grid.length - 1][grid[0].length - 1];
}
}