LeetCode: Distinct Subsequences 解题报告
Distinct Subsequences
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Here is an example:
S = "rabbbit", T = "rabbit"
Return 3.

SOLUTION 1(AC):
现在这种DP题目基本都是5分钟AC咯。主页君引一下别人的解释咯:
http://blog.csdn.net/fightforyourdream/article/details/17346385?reload#comments
http://blog.csdn.net/abcbc/article/details/8978146
引自以上的解释:
遇到这种两个串的问题,很容易想到DP。但是这道题的递推关系不明显。可以先尝试做一个二维的表int[][] dp,用来记录匹配子序列的个数(以S ="rabbbit",T = "rabbit"为例):
r a b b b i t
1 1 1 1 1 1 1 1
r 0 1 1 1 1 1 1 1
a 0 0 1 1 1 1 1 1
b 0 0 0 1 2 3 3 3
b 0 0 0 0 1 3 3 3
i 0 0 0 0 0 0 3 3
t 0 0 0 0 0 0 0 3
从这个表可以看出,无论T的字符与S的字符是否匹配,dp[i][j] = dp[i][j - 1].就是说,假设S已经匹配了j - 1个字符,得到匹配个数为dp[i][j - 1].现在无论S[j]是不是和T[i]匹配,匹配的个数至少是dp[i][j - 1]。除此之外,当S[j]和T[i]相等时,我们可以让S[j]和T[i]匹配,然后让S[j - 1]和T[i - 1]去匹配。所以递推关系为:
dp[0][0] = 1; // T和S都是空串.
dp[0][1 ... S.length() - 1] = 1; // T是空串,S只有一种子序列匹配。
dp[1 ... T.length() - 1][0] = 0; // S是空串,T不是空串,S没有子序列匹配。
dp[i][j] = dp[i][j - 1] + (T[i - 1] == S[j - 1] ? dp[i - 1][j - 1] : 0).1 <= i <= T.length(), 1 <= j <= S.length()
这道题可以作为两个字符串DP的典型:
两个字符串:
先创建二维数组存放答案,如解法数量。注意二维数组的长度要比原来字符串长度+1,因为要考虑第一个位置是空字符串。
然后考虑dp[i][j]和dp[i-1][j],dp[i][j-1],dp[i-1][j-1]的关系,如何通过判断S.charAt(i)和T.charAt(j)的是否相等来看看如果移除了最后两个字符,能不能把问题转化到子问题。
最后问题的答案就是dp[S.length()][T.length()]
还有就是要注意通过填表来找规律。
注意:循环的时候,一定要注意i的取值要到len,这个出好几次错了。
public class Solution {
public int numDistinct(String S, String T) {
if (S == null || T == null) {
return 0;
}
int lenS = S.length();
int lenT = T.length();
if (lenS < lenT) {
return 0;
}
int[][] D = new int[lenS + 1][lenT + 1];
// BUG 1: forget to use <= instead of <....
for (int i = 0; i <= lenS; i++) {
for (int j = 0; j <= lenT; j++) {
// both are empty.
if (i == 0 && j == 0) {
D[i][j] = 1;
} else if (i == 0) {
// S is empty, can't form a non-empty string.
D[i][j] = 0;
} else if (j == 0) {
// T is empty. S is not empty.
D[i][j] = 1;
} else {
D[i][j] = 0;
// keep the last character of S.
if (S.charAt(i - 1) == T.charAt(j - 1)) {
D[i][j] += D[i - 1][j - 1];
}
// discard the last character of S.
D[i][j] += D[i - 1][j];
}
}
}
return D[lenS][lenT];
}
}
运行时间:
| Submit Time | Status | Run Time | Language |
|---|---|---|---|
| 13 minutes ago | Accepted | 432 ms | java |
SOLUTION 2:
递归解法也写一下,蛮简单的:
但是这个解法过不了,TLE了。
// SOLUTION 2: recursion version.
public int numDistinct(String S, String T) {
if (S == null || T == null) {
return 0;
} return rec(S, T, 0, 0);
} public int rec(String S, String T, int indexS, int indexT) {
int lenS = S.length();
int lenT = T.length(); // base case:
if (indexT >= lenT) {
// T is empty.
return 1;
} if (indexS >= lenS) {
// S is empty but T is not empty.
return 0;
} int sum = 0;
// use the first character in S.
if (S.charAt(indexS) == T.charAt(indexT)) {
sum += rec(S, T, indexS + 1, indexT + 1);
} // Don't use the first character in S.
sum += rec(S, T, indexS + 1, indexT); return sum;
}
SOLUTION 3:
递归加上memory记忆之后,StackOverflowError. 可能还是不够优化。确实递归层次太多。
| Runtime Error Message: | Line 125: java.lang.StackOverflowError |
| Last executed input: | "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz |
// SOLUTION 3: recursion version with memory.
public int numDistinct(String S, String T) {
if (S == null || T == null) {
return 0;
} int lenS = S.length();
int lenT = T.length(); int[][] memory = new int[lenS + 1][lenT + 1];
for (int i = 0; i <= lenS; i++) {
for (int j = 0; j <= lenT; j++) {
memory[i][j] = -1;
}
} return rec(S, T, 0, 0, memory);
} public int rec(String S, String T, int indexS, int indexT, int[][] memory) {
int lenS = S.length();
int lenT = T.length(); // base case:
if (indexT >= lenT) {
// T is empty.
return 1;
} if (indexS >= lenS) {
// S is empty but T is not empty.
return 0;
} if (memory[indexS][indexT] != -1) {
return memory[indexS][indexT];
} int sum = 0;
// use the first character in S.
if (S.charAt(indexS) == T.charAt(indexT)) {
sum += rec(S, T, indexS + 1, indexT + 1);
} // Don't use the first character in S.
sum += rec(S, T, indexS + 1, indexT); // record the solution.
memory[indexS][indexT] = sum;
return sum;
}
SOLUTION 4 (AC):
参考了http://blog.csdn.net/fightforyourdream/article/details/17346385?reload#comments的代码后,发现递归过程找解的过程可以优化。我们不需要沿用DP的思路
而应该与permutation之类差不多,把当前可能可以取的解都去尝试一次。就是在S中找到T的首字母,再进一步递归。
| Submit Time | Status | Run Time | Language |
|---|---|---|---|
| 0 minutes ago | Accepted | 500 ms | java |
// SOLUTION 4: improved recursion version
public int numDistinct(String S, String T) {
if (S == null || T == null) {
return 0;
} int lenS = S.length();
int lenT = T.length(); int[][] memory = new int[lenS + 1][lenT + 1];
for (int i = 0; i <= lenS; i++) {
for (int j = 0; j <= lenT; j++) {
memory[i][j] = -1;
}
} return rec4(S, T, 0, 0, memory);
} public int rec4(String S, String T, int indexS, int indexT, int[][] memory) {
int lenS = S.length();
int lenT = T.length(); // base case:
if (indexT >= lenT) {
// T is empty.
return 1;
} if (indexS >= lenS) {
// S is empty but T is not empty.
return 0;
} if (memory[indexS][indexT] != -1) {
return memory[indexS][indexT];
} int sum = 0;
for (int i = indexS; i < lenS; i++) {
// choose which character in S to choose as the first character of T.
if (S.charAt(i) == T.charAt(indexT)) {
sum += rec4(S, T, i + 1, indexT + 1, memory);
}
} // record the solution.
memory[indexS][indexT] = sum;
return sum;
}
SOLUTION 5:
在SOLUTION 4的基础之上,把记忆体去掉之后,仍然是TLE
| Last executed input: | "daacaedaceacabbaabdccdaaeaebacddadcaeaacadbceaecddecdeedcebcdacdaebccdeebcbdeaccabcecbeeaadbccbaeccbbdaeadecabbbedceaddcdeabbcdaeadcddedddcececbeeabcbecaeadddeddccbdbcdcbceabcacddbbcedebbcaccac", "ceadbaa" |
// SOLUTION 5: improved recursion version without memory.
public int numDistinct(String S, String T) {
if (S == null || T == null) {
return 0;
} return rec5(S, T, 0, 0);
} public int rec5(String S, String T, int indexS, int indexT) {
int lenS = S.length();
int lenT = T.length(); // base case:
if (indexT >= lenT) {
// T is empty.
return 1;
} if (indexS >= lenS) {
// S is empty but T is not empty.
return 0;
} int sum = 0;
for (int i = indexS; i < lenS; i++) {
// choose which character in S to choose as the first character of T.
if (S.charAt(i) == T.charAt(indexT)) {
sum += rec5(S, T, i + 1, indexT + 1);
}
} return sum;
}
总结:
大家可以在SOLUTION 1和SOLUTION 4两个选择里用一个就好啦。
http://blog.csdn.net/fightforyourdream/article/details/17346385?reload#comments
这道题可以作为两个字符串DP的典型:
两个字符串:
先创建二维数组存放答案,如解法数量。注意二维数组的长度要比原来字符串长度+1,因为要考虑第一个位置是空字符串。
然后考虑dp[i][j]和dp[i-1][j],dp[i][j-1],dp[i-1][j-1]的关系,如何通过判断S.charAt(i)和T.charAt(j)的是否相等来看看如果移除了最后两个字符,能不能把问题转化到子问题。
最后问题的答案就是dp[S.length()][T.length()]
还有就是要注意通过填表来找规律。
GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dp/NumDistinct.java
LeetCode: Distinct Subsequences 解题报告的更多相关文章
- Leetcode 115 Distinct Subsequences 解题报告
Distinct Subsequences Total Accepted: 38466 Total Submissions: 143567My Submissions Question Solutio ...
- 【LeetCode】115. Distinct Subsequences 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 日期 题目地址:https://leetc ...
- [LeetCode] Distinct Subsequences 解题思路
Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...
- 【LeetCode】792. Number of Matching Subsequences 解题报告(Python)
[LeetCode]792. Number of Matching Subsequences 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...
- 【LeetCode】659. Split Array into Consecutive Subsequences 解题报告(Python)
[LeetCode]659. Split Array into Consecutive Subsequences 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id ...
- LeetCode: Combination Sum 解题报告
Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...
- 子序列 sub sequence问题,例:最长公共子序列,[LeetCode] Distinct Subsequences(求子序列个数)
引言 子序列和子字符串或者连续子集的不同之处在于,子序列不需要是原序列上连续的值. 对于子序列的题目,大多数需要用到DP的思想,因此,状态转移是关键. 这里摘录两个常见子序列问题及其解法. 例题1, ...
- [leetcode]Distinct Subsequences @ Python
原题地址:https://oj.leetcode.com/problems/distinct-subsequences/ 题意: Given a string S and a string T, co ...
- [LeetCode] Distinct Subsequences 不同的子序列
Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...
随机推荐
- ios实例开发精品文章推荐(8.12)11个处理触摸事件和多点触摸的JS库
11个处理触摸事件和多点触摸的JS库 触摸屏是现在所有智能手机的标配,还包括各种平板设备,而且很多桌面也慢慢在开始支持触摸操作.要开发支持触摸屏设备的Web应用,我们需要借助浏览器的触摸事件来实现. ...
- excel中的数据粘贴不全到plsql中,excel 粘贴后空白,Excel复制粘贴内容不全
http://zhidao.baidu.com/link?url=pHZQvfWJzI-lQjl4uP86q4GLcpYHu4o-fdjiYegJS0Cy5HEq5oz0YrUye3iHjmv5CJ3 ...
- ruby的sort方法的重新认识
ruby中的sort方法,这个方法可以加一个两个参数的block,这个block可以返回1 0 -1来表示这两个参数大于 等于 小于示例: str = ["192.160.175" ...
- elk架构图
一.概述 笔者为了节约宝贵的服务器资源,把一些可拆分的服务合并在同一台主机.大家可以根据自己的实际业务环境自由拆分,延伸架构.
- numpy、scipy、matplotlib、OpenCV安装及问题解决
1 numpy 概述 numpy是Numerical Python的缩写,释义为数值的Python numpy弥补了作为通用编程语言的Python在数值计算方面能力弱.速度慢的不足(numpy的底层是 ...
- git使一个非仓库型的工程可以推送
git config receive.denycurrentbranch false
- SharePoint利用HttpModule的Init方法实现全局初始化
接上篇 我们知道,HttpRuntime中会对每一个Request创建一个HttpApplication对象(HttpApplicationFactory从一个HttpApplication池来拿). ...
- 像网页开发一样调试ios程序
PonyDebugger https://github.com/square/PonyDebugger
- 开关电源9v,1A
- Ubuntu 添加安装字体
Ubuntu的美化当然少不了漂亮字体的支持,我有时会code一下,所以喜欢adobe的 source code pro(开源),安装步骤如下: (注:如果想导入的字体是一个单ttf文件的,可以直接双击 ...