动态规划小结 - 二维动态规划 - 时间复杂度 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) 有关
这种情况下,时间复杂度 O(n*n),空间复杂度往往可以优化为O(n)
例题 1
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.
时间复杂度 O(n*n),空间复杂度O(n)的解法。
这里用了个以前不用的技巧,当想把数组初始化为非0的值时,不用memset,而改用vector表示数组。
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
if(grid.size() == || grid[].size() == ) return ;
int H = grid.size(), W = grid[].size();
vector<int> path(W+, INT_MAX);
path[] = ;
for(int i = ; i <= H; ++i)
for(int j = ; j <= W; path[j] = min(path[j-], path[j]) + grid[i-][j-], ++j);
return path[W];
}
};
例题 2
Unique Paths II
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
Above is a 3 x 7 grid. How many possible unique paths are there?
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1
and 0
respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2
.
Note: m and n will be at most 100.
时间复杂度 O(n*n),空间复杂度O(n)
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
if(obstacleGrid.size() == || obstacleGrid[].size() == ) return ;
int H = obstacleGrid.size(), W = obstacleGrid[].size();
int paths[W+]; memset(paths, , sizeof(paths));
paths[] = (obstacleGrid[][] ? : );
for(int i = ; i <= H; ++i){
for(int j = ; j <= W; ++j){
paths[j] = (obstacleGrid[i-][j-] ? : paths[j-] + paths[j]);
}
}
return paths[W];
}
};
例题 3
很熟悉的 Edit Distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
类似的还有http://basicalgos.blogspot.com/上的 53. Edit Distance between strings
这道题目我们要设置两个变量,i和j, E(i, j) 表示word1中以i 结尾的子串到表示word2中以j 结尾的子串的距离。
状态转移方程借助53. Edit Distance between strings上的这张图片来说明:
LeetCode那道题的实现代码,时间复杂度 O(n*n),空间复杂度O(n)
class Solution {
public:
int minDistance(string word1, string word2) {
if(word1.empty() && word2.empty()) return ;
int len1 = word1.length(), len2 = word2.length();
int A[len2+]; int pre;
memset(A, , sizeof(A));
for(int i = ; i <= len1; ++i){
for(int j = ; j <= len2; ++j){
int Min = INT_MAX;
if(i > ) Min = min(A[j]+, Min);
if(j > ) Min = min(A[j-]+, Min);
if(i > && j > ) Min = min(Min, pre+(word1[i-] == word2[j-] ? : ));
if(i == && j == ) Min = ;
pre = A[j];
A[j] = Min;
}
}
return A[len2];
}
};
后记
棋盘型二维动态规划典型的题目还有“寻找最长公共子串(substring)”,“寻找最长公共子序列(subsequence)”。
这些都可以给出时间复杂度 O(n*n),空间复杂度O(n)的解。
动态规划小结 - 二维动态规划 - 时间复杂度 O(n*n)的棋盘型,题 [LeetCode] Minimum Path Sum,Unique Paths II,Edit Distance的更多相关文章
- LeetCode之“动态规划”:Minimum Path Sum && Unique Paths && Unique Paths II
之所以将这三道题放在一起,是因为这三道题非常类似. 1. Minimum Path Sum 题目链接 题目要求: Given a m x n grid filled with non-negative ...
- 二维动态规划——Interleaving String
97. Interleaving String Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2 ...
- 543A - Writing Code(二维动态规划)
题意:现在要写m行代码,总共有n个文件,现在给出第i个文件每行会出现v[i]个bug,问你在bug少于b的条件下有多少种安排 分析:定义dp[i][j][k],i个文件,用了j行代码,有k个bug 状 ...
- LEETCODE —— Unique Paths II [动态规划 Dynamic Programming]
唯一路径问题II Unique Paths II Follow up for "Unique Paths": Now consider if some obstacles are ...
- poj 2155:Matrix(二维线段树,矩阵取反,好题)
Matrix Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 17880 Accepted: 6709 Descripti ...
- [LeetCode] Unique Paths && Unique Paths II && Minimum Path Sum (动态规划之 Matrix DP )
Unique Paths https://oj.leetcode.com/problems/unique-paths/ A robot is located at the top-left corne ...
- Leetcode之动态规划(DP)专题-63. 不同路径 II(Unique Paths II)
Leetcode之动态规划(DP)专题-63. 不同路径 II(Unique Paths II) 初级题目:Leetcode之动态规划(DP)专题-62. 不同路径(Unique Paths) 一个机 ...
- Leetcode之动态规划(DP)专题-64. 最小路径和(Minimum Path Sum)
Leetcode之动态规划(DP)专题-64. 最小路径和(Minimum Path Sum) 给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小. ...
- [leetcode]304Range Sum Query 2D - Immutable动态规划计算二维数组中子数组的sum
303一维数组的升级版,方法就是用二维数组res存下从(0,0)到当前位置的sum,存的方法是动态规划,看着二维数组画圈比较好搞清楚其中的加减法 算子数组的sum的时候也是和存差不多的逻辑,就是某一部 ...
随机推荐
- HTML5+Bootstrap 学习笔记 1
HTML <header> 标签 <header> 标签定义文档的页眉(介绍信息),是 HTML 5 中的新标签. 参考资料: HTML <header> 标签 h ...
- oracle数据库分页原理
Oracle数据库的rownum 在Oracle数据库中,分页方式没有MySql这样简单,它需要依靠rownum来实现.Rownum表示一条记录的行号,值得注意的是它在获取每一行后才赋予.因此,想指定 ...
- 1.安装CDH5.12.x
安装方式安装前准备安装步骤安装过程修改/etc/hosts设置ssh 互信修改linux 系统设置安装JDK1.8安装python2.7安装mysql/postgreysql数据库安装ntp设置本地y ...
- Python高级编程-多线程
(一)进程线程概述: 很多同学都听说过,现代操作系统比如Mac OS X,UNIX,Linux,Windows等,都是支持“多任务”的操作系统. 什么叫“多任务”呢?简单地说,就是操作系统可以同时运行 ...
- Thunder团队第三周 - Scrum会议1
Scrum会议1 小组名称:Thunder 项目名称:i阅app Scrum Master:王航 工作照片: 杨梓瑞在拍照,所以不在照片中. 参会成员: 王航(Master):http://www.c ...
- 20162328蔡文琛week09
学号 2016-2017-2 <程序设计与数据结构>第X周学习总结 教材学习内容总结 数据库是为了其他程序提供数据的应用软件. 关系书就哭通过唯一的标识符在不同表的记录见建立了关系. JD ...
- Alpha 冲刺(3/10)
队名 火箭少男100 组长博客 林燊大哥 作业博客 Alpha 冲鸭鸭鸭! 成员冲刺阶段情况 林燊(组长) 过去两天完成了哪些任务 协调各成员之间的工作 协助后端界面的开发 搭建项目运行的服务器环境 ...
- 在html在添加cookie和读取cookie
1.保存cookie var oDate = new Date(); oDate.setDate(oDate.getDate() + );//有效期为30天 document.cookie = &qu ...
- 安装FastDFS+Nginx
安装FastDFS FastDFS开发者的GitHub地址为:https://github.com/happyfish100 打开上述链接,我们点击fastdfs–>release,发现最新版的 ...
- Nginx + Keepalived使用文档
第一步: 下载keepalived地址:http://www.keepalived.org/download.html 解压安装: tar -zxvf keepalived-1.2.18.tar.gz ...