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

假装没事ソ 提交于 2019-12-03 11:23:55

问题描述:

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];
}
};


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!