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 ...
随机推荐
- nginx init 官方启动脚本
#!/bin/sh # # nginx - this script starts and stops the nginx daemon # # chkconfig: - 85 15 # descrip ...
- google开发新人入职100天,聊聊自己的经验&教训 个人对编程和开发的理解 技术发展路线
新人入职100天,聊聊自己的经验&教训 这篇文章讲了什么? 如题,本屌入职100天之后的经验和教训,具体包含: 对开发的一点感悟. 对如何提问的一点见解. 对Google开发流程的吐槽. 如果 ...
- 利用图片中的exif元数据批量查找图片中所包含的GPS信息
在图片的exif(交换图像文件格式)中标准定义了如何存储图像和音频文件的标准,而在这些标签中往往存在了一些容易被人们忽视却又重要的东西. 有一款工具名为exiftool,可以快速的解析所有标签,并将结 ...
- Linux下DIR,dirent,stat等结构体详解(转)
最近在看Linux下文件操作相关章节,遇到了这么几个结构体,被搞的晕乎乎的,今日有空,仔细研究了一下,受益匪浅. 首先说说DIR这一结构体,以下为DIR结构体的定义: struct __dirstre ...
- 如何使用SetTimer
1.SetTimer定义在那里? SetTimer表示的是定义个定时器.根据定义指定的窗口,在指定的窗口(CWnd)中实现OnTimer事件,这样,就可以相应事件了. SetTimer有两个函数.一个 ...
- JavaScript三种方式改变标签css
原文地址:https://www.cnblogs.com/xiangru0921/p/6514225.html <body> <div id="div">这 ...
- C# 自定义控件入门
原文地址:http://www.itdaan.com/blog/2008/03/29/95500785fa538b3900b34ee824376e8b.html 这几天为了什么"评估&quo ...
- mfc怎么显示jpg png图像
如果是VS2005以上版本可以直接使用MFC自带的CImage类,如果不是可以用网上比较流行的CxImage,或者使用GDI+
- Python 文件 readlines() 方法
概述 Python 文件 readlines() 方法用于读取整个文件(所有行)到一个列表,可以由for... in ... 结构进行遍历.列表的每一行变成列表的每一个元素. 语法 readlines ...
- Python 文件 read() 方法
概述 Python 文件 read() 方法用于从文件中读取指定的字符数,如果未给定或为负则读取所有. 语法 read() 方法语法如下: fileObject.read([size]) 参数 siz ...