64. Minimum Path Sum
Problem:
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
思路:
利用DP算法,到点(i,j)的最短路径和由公式:S[i][j] = min(S[i-1][j], S[i][j-1]) + grid[i][j]确定。注意到达边界上的点只有一条路径(只能一直向右或者一直向下),故边界上的点(i,0)与(0,j)最短路径由下面的公式确定:S[i][0] = S[i-1][0] + grid[i][0],S[0][j] = S[0][j-1] + grid[0][j]。
Solution:
int minPathSum(vector<vector<int>>& grid) {
if (grid.empty() || grid[0].empty()) return 0;
int m = grid.size(), n = grid[0].size();
vector<vector<int>> S(m, vector<int>(n, grid[0][0]));
for (int i = 1; i < m; i++) S[i][0] = S[i-1][0] + grid[i][0];
for (int j = 1; j < n; j++) S[0][j] = S[0][j-1] + grid[0][j];
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
S[i][j] = min(S[i-1][j], S[i][j-1]) + grid[i][j];
}
}
return S[m-1][n-1];
}
性能:
Runtime: 12 ms Memory Usage: 10.8 MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
![](https://www.cnblogs.com/images/cnblogs_com/dysjtu1995/1468066/t_qrcode_for_gh_547d3edeac81_258.jpg)
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。