LeetCode 笔记系列 20 Interleaving String [动态规划的抽象]
题目: Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc"
,
s2 = "dbbca"
,
When s3 = "aadbbcbcac"
, return true.
When s3 = "aadbbbaccc"
, return false.
这个题目值得记录的原因除了自己的解法没有通过大集合以外,主要还在与对动态规划的理解。在这两个月研究算法的过程中,我发现自己更倾向于直观的理解,而抽象思维上相对较弱。我们以这道题做个例子。
直观上,我看到该题,就会去想,s1取一部分,s2取一部分,然后再s1取一部分,反复知道匹配完成s3,算法去模拟这样的操作。
而当s1和s3匹配了一部分的时候,剩下s1‘和剩下的s3‘与s2又是一个子问题。这样很容易写成一个递归,但是需要注意两点:
1. 递归方法中,我们总是拿s1首先去匹配s3,如果不匹配,直接返回false。这样做的原因是保持匹配是“交替”进行的;
2. 当出现既可以匹配s1,又可以匹配s2的时候,一样可以通过递归来解决,看下面的代码。
private boolean isInterleaveInternal(String s1, String s2, String s3){
if(s1.equals("")) {
return s2.equals("") && s3.equals("");
}
if(s1.equals(s3) && s2.endsWith("")) return true;
int i1 = 0;
int i2 = 0;
int i3 = 0;
if(s1.charAt(0) != s3.charAt(0)) return false;
while(i1 < s1.length() && i2 < s2.length() && i3 < s3.length() &&
s1.charAt(i1) == s3.charAt(i3)) {
i1++;
i3++;
//如果这里s2也可以匹配s3,那么我们立马递归进行匹配
if(s2.charAt(i2) == s3.charAt(i3) && isInterleaveInternal(s2.substring(i2), s1.substring(i1), s3.substring(i3)))
return true;
}
//接下来开始匹配s2
return isInterleaveInternal(s2, s1.substring(i1), s3.substring(i3)); }
所以在调用这个方法的时候,也比较复杂,需要保证一定是s1首先匹配s3.
public boolean isInterleave(String s1, String s2, String s3) {
// Start typing your Java solution below
// DO NOT write main() function
if(s1.length() + s2.length() != s3.length()) return false;
if(s1.equals("") || s2.equals("") || s3.equals("")) {
if(s3.equals("")) return s1.equals("") && s2.equals("");
else return s1.equals(s3) || s2.equals(s3);
}
if(s1.charAt(0) == s3.charAt(0)) {
if(s2.charAt(0) != s3.charAt(0)) {
return isInterleaveInternal(s1, s2, s3);
}else {
if(isInterleaveInternal(s1, s2, s3)) return true;
else return isInterleaveInternal(s2, s1, s3);
}
}else if(s2.charAt(0) == s3.charAt(0)) return isInterleave(s2, s1, s3);
else return false;
}
这个办法看上去蛮直观的,是我马上能想到的,而且也是收到前面递归方法的影响。
但是大集合会超时,而且不好的地方是主函数有挺多的条件判断,显得不够简洁。
于是我们参考了这里的动态规划方法。
动态规划矩阵matched[l1][l2]表示s1取l1长度(最后一个字母的pos是l1-1),s2取l2长度(最后一个字母的pos是l2-1),是否能匹配s3的l1+12长度。
那么,我们有
matched[l1][l2] = s1[l1-1] == s3[l1+l2-1] && matched[l1-1][l2] || s2[l2 - 1] == s3[l1+l2-1] && matched[l1][l2-1]
边界条件是,其中一个长度为0,另一个去匹配s3.
这里s1和s2交替出现的规律并不明显,所以没有直观地想到。
代码如下:
public boolean isInterleave2(String s1, String s2, String s3){
if(s1.length() + s2.length() != s3.length()) return false;
boolean[][] matched = new boolean[s1.length() + 1][s2.length() + 1];
matched[0][0] = true;
for(int i1 = 1; i1 <= s1.length(); i1++){
if(s3.charAt(i1-1) == s1.charAt(i1-1)) {
matched[i1][0] = true;
}else break;
}
for(int i2 = 1; i2 <= s2.length(); i2++){
if(s3.charAt(i2 - 1) == s2.charAt(i2 - 1)) {
matched[0][i2] = true;
}else break;
} for(int i1 = 1; i1 <= s1.length(); i1++){
char c1 = s1.charAt(i1 - 1);
for(int i2 = 1; i2 <= s2.length(); i2++){
int i3 = i1 + i2;
char c2 = s2.charAt(i2 - 1);
char c3 = s3.charAt(i3 - 1);
if(c1 == c3){
matched[i1][i2] |= matched[i1 - 1][i2];
}
if(c2 == c3){
matched[i1][i2] |= matched[i1][i2 - 1];
}
}
}
return matched[s1.length()][s2.length()];
}
总结下:
1)递归能写出比较清晰简单的代码,但是有比较高的时间复杂度;
2)在递归不满足条件的情况下,动态规划是个比较好的选择;
3)一般来说,独立变量的个数决定动态规划的维度,例如l1和l2独立变化,所以用了二维动态规划。
LeetCode 笔记系列 20 Interleaving String [动态规划的抽象]的更多相关文章
- LeetCode 笔记系列 19 Scramble String [合理使用递归]
题目: Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty subs ...
- LeetCode(97) Interleaving String
题目 Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: ...
- LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
题目:Given a string S and a string T, find the minimum window in S which will contain all the characte ...
- LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]
题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...
- LeetCode 笔记系列 18 Maximal Rectangle [学以致用]
题目: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones ...
- LeetCode 笔记系列16.2 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
题目:Given a string S and a string T, find the minimum window in S which will contain all the characte ...
- LeetCode 笔记系列16.1 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
题目: Given a string S and a string T, find the minimum window in S which will contain all the charact ...
- LeetCode 笔记系列五 Generate Parentheses
题目: Given n pairs of parentheses, write a function to generate all combinations of well-formed paren ...
- LeetCode 笔记系列13 Jump Game II [去掉不必要的计算]
题目: Given an array of non-negative integers, you are initially positioned at the first index of the ...
随机推荐
- [windows API]获取当前系统图标,文字大小
取DPI 缩放比例 HWND wnd = ::GetDesktopWindow(); dbg_print("desktopwnd:0x%X\n",wnd); HDC dc = G ...
- [课程设计]Scrum 1. 8多鱼点餐系统开发进度(完善整个订餐页面工作)
[课程设计]Scrum 1. 8多鱼点餐系统开发进度(完善整个订餐页面工作) 1.团队名称:重案组 2.团队目标:长期经营,积累客户充分准备,伺机而行 3.团队口号:矢志不渝,追求完美 4.团队选题: ...
- 浙江理工2015.12校赛-G Jug Hard
Jug Hard Time Limit: 10 Sec Memory Limit: 128 MB Submit: 1172 Solved: 180 Description You have two e ...
- .Net最佳实践3:使用性能计数器收集性能数据
本文值得阅读吗? 本文讨论我们如何使用性能计数器从应用程序收集数据.我们将先了解的基本知识,然后我们将看到一个简单的示例,我们将从中收集一些性能数据. 介绍: - 我的应用程序的性能是最好的,像火箭 ...
- ms sql 经典语句【珍藏】
数据库中字段中有不需要"[演示数据请勿真实购买]" 例如: update Hishop_Products set ProductName = replace(ProductName ...
- hdu 3887 Counting Offspring dfs序+树状数组
Counting Offspring Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Othe ...
- 学习mongo系列(十)MongoDB 备份(mongodump)与恢复(mongorerstore) 监控(mongostat mongotop)
一.备份 在Mongodb中我们使用mongodump命令来备份MongoDB数据.该命令可以导出所有数据到指定目录中. mongodump命令可以通过参数指定导出的数据量级转存的服务器. mongo ...
- 学习mongo系列(五) AND,$or,$type
MongoDB OR 条件 MongoDB OR 条件语句使用了关键字 $or,语法格式如下: >db.col.find( { $or: [ {key1: value1}, {key2:valu ...
- Mysql 中有关日期的函数(sql)
DAYOFWEEK(date)返回日期date的星期索引(1=星期天,2=星期一, ……7=星期六).这些索引值对应于ODBC标准.mysql> select DAYOFWEEK('1998-0 ...
- openfire源码修改聊天消息发送内容
/** * $RCSfile: MessageRouter.java,v $ * $Revision: 3007 $ * $Date: 2005-10-31 13:29:25 -0300 (Mon, ...