题目: Given s1s2s3, 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 [动态规划的抽象]的更多相关文章

  1. LeetCode 笔记系列 19 Scramble String [合理使用递归]

    题目: Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty subs ...

  2. LeetCode(97) Interleaving String

    题目 Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: ...

  3. 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 ...

  4. LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]

    题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...

  5. LeetCode 笔记系列 18 Maximal Rectangle [学以致用]

    题目: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones ...

  6. 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 ...

  7. 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 ...

  8. LeetCode 笔记系列五 Generate Parentheses

    题目: Given n pairs of parentheses, write a function to generate all combinations of well-formed paren ...

  9. LeetCode 笔记系列13 Jump Game II [去掉不必要的计算]

    题目: Given an array of non-negative integers, you are initially positioned at the first index of the ...

随机推荐

  1. 【转】本地存储-localStroage/sessionStorage存储

    原文地址:[js学习笔记-103]----本地存储-localStroage/sessionStorage存储 客户端存储 l  WEB存储 web存储最初作为html5的一部分被定义成API形式,但 ...

  2. 微信JS SDK PHP Demo

    一.JSSDK类定义 <?php class JSSDK { private $appId; private $appSecret; public function __construct($a ...

  3. Knights of the Round Table-POJ2942(双连通分量+交叉染色)

    Knights of the Round Table Description Being a knight is a very attractive career: searching for the ...

  4. [问题2014A05] 解答

    [问题2014A05]  解答 (1) 将矩阵 \(A\) 分解为两个矩阵的乘积: \[A=\begin{bmatrix} 1 & 1 & \cdots & 1 & 1 ...

  5. USB port 如何识别不同的Charger类型

    基于Qualcom 8960/8921平台 一,软件分析 1.  USB charger types & Power supply types USB_INVALID_CHARGER      ...

  6. 【Unity】常用代码

    //父子节点相关的: parent 变量表示Transform的父节点 root 表示它的根节点,如果没有父节点,它会返回自己 //根据名字查找子节点 Transform Find(string na ...

  7. GaugeControl 数字时钟,温度计,仪表盘

    https://documentation.devexpress.com/#WindowsForms/CustomDocument18217 This topic will guide you thr ...

  8. gitlab open ssl

    cd /home/git/gitlab/ sudo -u git -H vi config/gitlab.yml sudo -u git -H vi /home/git/gitlab-shell/co ...

  9. python __file__ 与argv[0]

    在python下,获取当前执行主脚本的方法有两个:sys.argv[0]和__file__. sys.argv[0] 获取主执行文件路径的最佳方法是用sys.argv[0],它可能是一个相对路径,所以 ...

  10. php新手常用的函数(随时更新)

    //数字保留两位小数 $n = sprintf("%1.2f", $n); //方法二 $n = number_format($n, 2, '.', ''); //UTF8转GBK ...