LeetCode:Minimum Path Sum(网格最大路径和)
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.
典型的动态规划问题。
设dp[i][j]表示从左上角到grid[i][j]的最小路径和。那么dp[i][j] = grid[i][j] + min( dp[i-1][j], dp[i][j-1] );
下面的代码中,为了处理计算第一行和第一列的边界条件,我们令dp[i][j]表示从左上角到grid[i-1][j-1]的最小路径和,最后dp[m][n]是我们所求的结果
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
int row = grid.size(),col;
if(row == 0)return 0;
else col = grid[0].size();
vector<vector<int> >dp(row+1, vector<int>(col+1, INT_MAX));
dp[0][1] = 0;
for(int i = 1; i <= row; i++)
for(int j = 1; j <= col; j++)
dp[i][j] = grid[i-1][j-1] + min(dp[i][j-1], dp[i-1][j]);
return dp[row][col];
}
};
注意到上面的代码中dp[i][j] 只和上一行的dp[i-1][j]和上一列的dp[i][j-1]有关,因此可以优化空间为O(n)(准确来讲空间复杂度可以是O(min(row,col
))) 本文地址
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
int row = grid.size(),col;
if(row == 0)return 0;
else col = grid[0].size();
vector<int >dp(col+1, INT_MAX);
dp[1] = 0;
for(int i = 1; i <= row; i++)
for(int j = 1; j <= col; j++)
dp[j] = grid[i-1][j-1] + min(dp[j], dp[j-1]);
return dp[col];
}
};
问题扩展
最大路径和只需要把上面的递推公式中的min换成max。
现在有个问题,如果两个人同时从左上角出发,目的地是右下角,两个人的路线不能相交(即除了出发点和终点外,两个人不同通过同一个格子),使得两条路径的和最大。(这和一个人先从左上角到右下角,再回到左上角是相同的问题)。
这是双线程动态规划问题:假设网格为grid,dp[k][i][j]表示两个人都走了k步,第一个人向右走了i步,第二个人向右走了j步 时的最大路径和(只需要三个变量就可以定位出两个人的位置grid[k-i][i-1] 、 grid[k-j][j-1]),那么
dp[k][i][j] = max(dp[k-1][i-1][j-1], dp[k-1][i][j], dp[k-1][i-1][j], dp[k-1][i][j-1]) + grid[k-i][i-1] + grid[k-j][j-1] (我们假设在起始位置时就已经走了一步)
这个方程的意思是从第k-1步到第k步,可以两个人都向右走、都向下走、第一个向下第二个向右、第一个向右第二个向下,这四种走法中选择上一步中路径和最大的。
由于要保证两条路线不能相交,即两个人走的过程中,有一个人向右走的步数永远大于另一个人向右走的步数,我们不妨设第二个人向右走的步数较大,即dp[k][i][j]中j > i才是有效的状态。走到终点的步数为:网格的行数+网格的列数-1
需要注意的是:当走了k步时,某个人向右走的步数必须 > k - 网格的行数,如果向右走的步数 <= k-行数,那么向下走的步数 = k-向右走的步数 >= 行数,此时超出了网格的范围。由于我们假设了 j > i,因此只要保证 i > k-网格行数即可。
代码如下:
int max2PathSum(vector<vector<int> > grid)
{
int row = grid.size(), col = grid[0].size();
vector<vector<vector<int> > > dp(row+col, vector<vector<int> >(col+1, vector<int>(col+1, 0)));
for(int step = 2; step <= row+col-2; step++)
for(int i = max(1, step-row+1); i <= step && i <= col; i++)
for(int j = i+1; j <= step && j <= col; j++)
{ dp[step][i][j] = max(max(dp[step-1][i][j], dp[step-1][i-1][j-1]), max(dp[step-1][i-1][j], dp[step-1][i][j-1]));
dp[step][i][j] += (grid[step-i][i-1] + grid[step-j][j-1]);
}
return dp[row+col-2][col-1][col] + 2*grid[row-1][col-1] + 2*grid[0][0];
}
我们最终的目标是dp[row+col-1][col][col] = max{dp[row+col-2][col-1][col-1], dp[row+col-2][col][col], dp[row+col-2][col-1][col], dp[row+col-2][col][col-1]} + 2*grid[row-1][col-1]
由于dp[row+col-2][col-1][col-1], dp[row+col-2][col][col], dp[row+col-2][col][col-1]都是无效的状态(dp[k][i][j]中j > i才是有效的状态),
所以dp[row+col-1][col][col] = dp[row+col-2][col-1][col] + 2*grid[row-1][col-1],代码中最后结果还加上了所在起点的的网格值。
由以上可知,循环中最多只需要求到了dp[row+col-2][][]。
nyoj中 传纸条(一)就是这个问题,可以在这一题中测试上述函数的正确性,测试代码如下:
int main()
{
int n;
scanf("%d",&n);
for(int i = 1; i <= n; i++)
{
int row, col;
scanf("%d%d", &row, &col);
vector<vector<int> >grid(row, vector<int>(col));
for(int a = 0; a < row; a++)
for(int b = 0; b < col; b++)
scanf("%d", &grid[a][b]);
printf("%d\n", max2PathSum(grid));
}
return 0;
}
这个问题还可以使用最小费用流来解决,具体可以参考here
【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3774804.html
LeetCode:Minimum Path Sum(网格最大路径和)的更多相关文章
- LeetCode: Minimum Path Sum 解题报告
Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to b ...
- 动态规划小结 - 二维动态规划 - 时间复杂度 O(n*n)的棋盘型,题 [LeetCode] Minimum Path Sum,Unique Paths II,Edit Distance
引言 二维动态规划中最常见的是棋盘型二维动态规划. 即 func(i, j) 往往只和 func(i-1, j-1), func(i-1, j) 以及 func(i, j-1) 有关 这种情况下,时间 ...
- [LeetCode] 113. Path Sum II 二叉树路径之和之二
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- [LeetCode] 112. Path Sum 二叉树的路径和
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...
- LeetCode 437. Path Sum III (路径之和之三)
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- [LeetCode] Minimum Path Sum 最小路径和
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which ...
- LeetCode OJ:Minimum Path Sum(最小路径和)
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which ...
- Leetcode Minimum Path Sum
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which ...
- LeetCode 112. Path Sum (二叉树路径之和)
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...
随机推荐
- 从DNS配置
从服务器可以从主服务器上抓取指定的区域数据文件起到备份解析记录和负载均衡的作用. 主DNS服务器IP:192.168.16.20 从DNS服务器IP:192.168.16.30 1,修改主服务器区域配 ...
- __slots__ 属性绑定
s = Student() # 创建新的实例 s.name = 'Michael' # 绑定属性'name' s.age = 25 # 绑定属性'age' s.score = 99 # 绑定属性'sc ...
- jquery基本选择器,一张页面全搞定
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- java 字符串截取
截取指定长度的字符串,如果超出就用more的内容来替换 截取的字节数,截取的时候,有可能会少截取一位(当最后一位是1个双字节的话,会少截取一个) public class Test { publ ...
- js 格式化日期 ("/Date(1400046388387)/")
var date = new Date(parseInt(str.replace(/\/Date\((-?\d+)\)\//, '$1'))); var d= date.getFullYear() + ...
- 自己写ORM框架 DBUtils_DG Java(C#的写在链接里)
ORM框架想必大家都比较熟知了,即对象关系映射(英语:Object Relation Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同 ...
- D3 学习资源
发现这个网站还是挺不错的:http://www.ourd3js.com/wordpress/
- WP8:在Cocos2d-x中使用OpenXLive
一. Cocos2d-x for Windows Phone 到2013年底,几大手游引擎都陆续支持WP8了,特别是Unity3D和Cocos2d-x.有过游戏开发经验的朋友们应该对这两个引擎不 ...
- 一步一步搭建客服系统 (4) 客户列表 - JS($.ajax)调用WCF 遇到的各种坑
本文以一个生成.获取“客户列表”的demo来介绍如何用js调用wcf,以及遇到的各种问题. 1 创建WCF服务 1.1 定义接口 创建一个接口,指定用json的格式: [ServiceContra ...
- Dynamic CRM 2013学习笔记(七)追踪、监控及性能优化
本文将介绍CRM的三个内容追踪.监控及性能优化.追踪是CRM里一个很有用的功能,它能为我们的CRM调试或解决错误.警告提供有价值的信息:我们可以用window的性能监控工具来了解CRM的性能状况:最后 ...