中山大学算法课程题目详解(第十三周)
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]; } };
相关文章推荐
- 中山大学算法课程题目详解(第十周)
- 中山大学算法课程题目详解(第四周)
- 中山大学算法课程题目详解(第十五周)
- 中山大学算法课程题目详解(第五周)
- 中山大学算法课程题目详解(第一周)
- 中山大学算法课程题目详解(第七周)
- 中山大学算法课程题目详解(第十一周)
- 中山大学算法课程题目详解(第十四周)
- 中山大学算法课程题目详解(第十二周)
- 中山大学算法课程题目详解(第十六周)
- 中山大学算法课程题目详解(第十八周)
- 中山大学算法课程题目详解(第六周)
- 中山大学算法课程题目详解(第十九周)NP问题
- 中山大学算法课程题目详解(第三周)
- 中山大学算法课程题目详解(第十七周)
- 精选微软经典的算法面试100题(第1-20题) -代码详解(题目选自“结构之法”大侠的博客,答案都是本菜鸟自己做的)
- 【python数据挖掘课程】二十.KNN最近邻分类算法分析详解及平衡秤TXT数据集读取
- 算法分析与设计课程作业第十三周#1#2#3
- 支持向量机—SMO论文详解(序列最小最优化算法)
- 零零散散学算法之详解二叉查找树