这道是非常非常典型的动态规划问题,以前读书的时候记得老师讲的时候死活听不懂,现在工作了几年后,维基百科看了一些介绍,手写一遍AC通过。
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> sum(m,vector<int>(n,grid[0][0]));
for(int i = 1;i < m;i++)
sum[i][0] = sum[i-1][0] + grid[i][0];
for(int j = 1;j < n;j++)
sum[0][j] = sum[0][j - 1] + grid[0][j];
for(int i = 1;i < m;i++)
for(int j = 1;j < n;j++)
sum[i][j] = min(sum[i-1][j],sum[i][j-1]) + grid[i][j];
return sum[m-1][n-1];
}
};
这道题是先把第一行和第一列的距离算出来,我们从开始位置触发,要么向下,要么向右,因此从起点慢慢从上往下 从左往右计算,最终sum最右下角数据即为结果。
当我洋洋得意的打开讨论区看到大神一篇帖子里,初始版本解法和我上面代码基本一样,难道我还存在更牛的解法?上面程序执行结果:
Runtime: 20 ms, faster than 59.19% of C++ online submissions for Minimum Path Sum.
Memory Usage: 10.5 MB, less than 9.39% of C++ online submissions for Minimum Path Sum.
速度更快解法,相对难懂,gdb跟两编就会有个清晰的理解,相对于方法一少了一个循环:
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<int> cur(m, grid[0][0]);
for (int i = 1; i < m; i++)
cur[i] = cur[i - 1] + grid[i][0];
for (int j = 1; j < n; j++) {
cur[0] += grid[0][j];
for (int i = 1; i < m; i++)
cur[i] = min(cur[i - 1], cur[i]) + grid[i][j];
}
return cur[m - 1];
}
};
执行结果:
Runtime: 16 ms, faster than 91.86% of C++ online submissions for Minimum Path Sum.
Memory Usage: 10.2 MB, less than 9.39% of C++ online submissions for Minimum Path Sum.
可调试版本程序:
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <list>
using namespace std;
int minPathSum(vector<vector<int>>& grid)
{
int m = grid.size();
int n = grid[0].size();
vector<int> cur(m, grid[0][0]);
for (int i = 1; i < m; i++)
cur[i] = cur[i - 1] + grid[i][0];
for (int j = 1; j < n; j++) {
cur[0] += grid[0][j];
for (int i = 1; i < m; i++)
cur[i] = min(cur[i - 1], cur[i]) + grid[i][j];
}
return cur[m - 1];
}
int main()
{
vector<vector<int>> path{{1,3,1},{1,5,1},{4,2,1}};
cout << minPathSum(path);
return 0;
}