分析
-
本题的考点:动态规划。
-
状态表示
f[i][j]
:从起点到达坐标点(i, j)
的所有路径中权值和的最小值。 -
状态转移:
f[i][j] = min(f[i-1][j], f[i][j-1]) + grid[i][j]
。
代码
- C++
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
vector<vector<int>> f(n, vector<int>(m, INT_MAX));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (!i && !j) f[i][j] = grid[i][j];
else {
if (i) f[i][j] = min(f[i][j], f[i - 1][j] + grid[i][j]);
if (j) f[i][j] = min(f[i][j], f[i][j - 1] + grid[i][j]);
}
return f[n - 1][m - 1];
}
};
- Java
class Solution {
public int minPathSum(int[][] grid) {
int n = grid.length, m = grid[0].length;
int[][] f = new int[n][m];
for (int i = 0; i < n; i++) Arrays.fill(f[i], Integer.MAX_VALUE);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (i == 0 && j == 0) f[i][j] = grid[i][j];
else {
if (i != 0) f[i][j] = Math.min(f[i][j], f[i - 1][j] + grid[i][j]);
if (j != 0) f[i][j] = Math.min(f[i][j], f[i][j - 1] + grid[i][j]);
}
return f[n - 1][m - 1];
}
}
时空复杂度分析
-
时间复杂度:$O(n \times m)$,
m、n
为行数、列数。 -
空间复杂度:$O(n \times m)$。