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.5)
IOS基础知识记录 IOS基础知识记录一 http://www.apkbus.com/android-131902-1-1.htmlIOS基础知识记录二 http://ww ...
- PHP 5.3版本上MS SQL Server的连接配置
折腾了好久,最后终于连接成功了! 注:我使用的的phpStudy. php.ini中配置: ;这是php中带的驱动 extension=php_sqlsrv.dll extension=php_pdo ...
- windbg(1)
1.http://www.cnblogs.com/huangyong9527/category/384128.html 2.http://www.cnblogs.com/pugang/category ...
- POJ 1486 Sorting Slides (KM)
Sorting Slides Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 2831 Accepted: 1076 De ...
- js验证身份证类
var idCardNoUtil = { provinceAndCitys: {11:"北京",12:"天津",13:"河北",14:&qu ...
- Oracle2MySQL注意事项
在Oracle切换成MySQL时,会碰到如下注意事项: Oracle中的sysdate在MySQL中是不支持的: Oracle中的分布方案在MySQL中的实现: Oracle中的SQL语句是大小写不敏 ...
- JSON之Asp.net MVC C#对象转JSON,DataTable转JSON,List<T>转JSON,JSON转List<T>,JSON转C#对象
一.JSON解析与字符串化 JSON.stringify() 序列化对象.数组或原始值 语法:JSON.stringify(o,filter,indent) o,要转换成JSON的对象.数组或原始值 ...
- 记github上搭建独立域名的免费博客的方法过程
前提:拥有github帐号,linux上安装好了git. 全局路线: 1. 设计一个你想要的二级域名,并在git上创建一个以[二级域名.github.com]作为项目名的repository. 过程详 ...
- 第3章 Python基础-文件操作&函数 文件操作 练习题
一.利用b模式,编写一个cp工具,要求如下: 1. 既可以拷贝文本又可以拷贝视频,图片等文件 2. 用户一旦参数错误,打印命令的正确使用方法,如usage: cp source_file target ...
- CSS margin属性与用法教程
margin 属性是css用于在一个声明中设置所有 margin 属性的简写属性,margin是css控制块级元素之间的距离, 它们之间是透明不可见的. margin属性包含了margin left ...