您的位置:首页 > 其它

中山大学算法课程题目详解(第十三周)

2017-12-28 09:23 323 查看

问题描述:

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 1:

[[1,3,1],
[1,5,1],
[4,2,1]]

Given the above grid map, return 
7
.
Because the path 1→3→1→1→1 minimizes the sum.

解决思路:

当然,采用动态规划的方法,从左上到右下开始进行递推。
首先,对于边界做以下处理:
(1)result[i][0] = result[i - 1][0] + grid[i][0]

(2)result[0][i] = result[0][i - 1] + grid[0][i]
接着,对于其他采用 result[i][j] = min(result[i - 1][j], result[i][j - 1]) + grid[i][j]

具体代码实现:

class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int row = grid.size();
int col = grid[0].size();

vector<vector<int> > result(row);
for (int i = 0; i < row; i++) {
result[i].resize(col, 0);
}
result[0][0] = grid[0][0];

for (int i = 1; i < row; i++) {
result[i][0] = result[i - 1][0] + grid[i][0];
}

for (int i = 1; i < col; i++) {
result[0][i] = result[0][i - 1] + grid[0][i];
}

for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
result[i][j] = min(result[i - 1][j], result[i][j - 1]) + grid[i][j];
}
}

return result[row - 1][col - 1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: