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 ...
随机推荐
- kickstart命令选项
下面的选项可以放入kickstart文件.如果喜欢使用图形化的界面来创建kickstart文件,可以使用"Kickstart配置"应用程序.(注:如果某选项后面跟随了一个等号(=) ...
- 【Spring】SpringMVC非注解配置的两种方式
目录结构: contents structure [+] SpringMVC是什么 Spring MVC的设计原理 SpringMVC配置的第一种方式 1,复制Jar包 2,Web.xml文件 3,M ...
- 创建 maven maven-archetype-quickstart 项目抱错问题解决方法
问题: eclipse装m2eclipse的时候装完后创建项目的时候报错: Unable to create project from archetype org.apache.maven.arche ...
- 【web】a标签点击时跳出确认框
[web]a标签点击时跳出确认框 https://blog.csdn.net/michael_ouyang/article/details/52765575需求如下: 在跳转链接前,需要判断该用户是否 ...
- numpy 中的axis轴问题
在numpy库中,axis轴的问题比较重要,不同的值会得到不同的结果,为了便于理解,特此将自己的理解进行梳理 为了梳理axis,借助于sum函数进行! a = np.arange(27).reshap ...
- JsonPath小结
在查看DHC Assertions 模块说明的时候,无意间发现assert模块中JsonBody使用了 JSON Path ,兴趣使然,看了下,发现是类似解析xml用到的 XPath.通过路径来获取j ...
- 安卓7.0遇到 android.os.FileUriExposedException: file:///storage/emulated.. exposed beyond app through Intent.getData()
1.在AndroidManifest.xml中添加如下代码 <?xml version="1.0" encoding="utf-8"?> <m ...
- Mac OS下Android Studio的Java not found问题,androidfound
Android Studio正式版已经发布一段时间了,使用Mac版的Android Studio可能与遇到Java not found:Android Studio was unable to fin ...
- 启动mysql报错 -- ERROR! The server quit without updating PID file
开发说某个测试环境的mysql,无法重启了,报以下错误提示: # service mysqld restart Shutting down MySQL.. SUCCESS! Starting MySQ ...
- process credentials(三)
主要内容包括: 1.进程描述符中Realtime Mutex相关数据结构的初始化 2.子进程如何复制父进程的credentials 3.per-task delay accounting的处理 4.子 ...