您的位置:首页 > 其它

算法分析与设计丨第十二周丨LeetCode(16)——Minimum Path Sum(Medium)

2017-11-28 20:18 375 查看
动态规划

题目链接:https://leetcode.com/problems/minimum-path-sum/description/

题目描述:

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizesthe 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.
题目解析:今天看了一天的动态规划,才有一点明朗,要加紧刷题了。这是一道典型的动态规划,将问题化为一个个子问题求解。

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

vector<vector<int> > temp_map(row_num,vector<int>(col_num,0));

temp_map[0][0] = grid[0][0];
for(int i = 1;i < row_num; ++i)
temp_map[i][0] = grid[i][0] + temp_map[i-1][0];
for(int i = 1;i < col_num; ++i)
temp_map[0][i] = grid[0][i] + temp_map[0][i-1];

for(int i = 1;i < row_num; ++i)
for(int j = 1;j < col_num; ++j)
{
temp_map[i][j] = min(temp_map[i-1][j],temp_map[i][j-1]) + grid[i][j];
//cout<<temp_map[i][j];
}

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