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

0 1 1 1 1 1 1 1

a 0 1 1 1 1 1 1

b 0 0 2 3 3 3

b 0 0 0 0 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 解题报告的更多相关文章

  1. Leetcode 115 Distinct Subsequences 解题报告

    Distinct Subsequences Total Accepted: 38466 Total Submissions: 143567My Submissions Question Solutio ...

  2. 【LeetCode】115. Distinct Subsequences 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 日期 题目地址:https://leetc ...

  3. [LeetCode] Distinct Subsequences 解题思路

    Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...

  4. 【LeetCode】792. Number of Matching Subsequences 解题报告(Python)

    [LeetCode]792. Number of Matching Subsequences 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...

  5. 【LeetCode】659. Split Array into Consecutive Subsequences 解题报告(Python)

    [LeetCode]659. Split Array into Consecutive Subsequences 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id ...

  6. LeetCode: Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

  7. 子序列 sub sequence问题,例:最长公共子序列,[LeetCode] Distinct Subsequences(求子序列个数)

    引言 子序列和子字符串或者连续子集的不同之处在于,子序列不需要是原序列上连续的值. 对于子序列的题目,大多数需要用到DP的思想,因此,状态转移是关键. 这里摘录两个常见子序列问题及其解法. 例题1, ...

  8. [leetcode]Distinct Subsequences @ Python

    原题地址:https://oj.leetcode.com/problems/distinct-subsequences/ 题意: Given a string S and a string T, co ...

  9. [LeetCode] Distinct Subsequences 不同的子序列

    Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...

随机推荐

  1. DPDK的安装与绑定网卡(转)

    from:http://www.cnblogs.com/mylinuxer/p/4274178.html DPDK的安装与绑定网卡 DPDK的安装有两种方法: 第一种是使用dpdk/tools/set ...

  2. 程序员,不要让自己做兔子(updated) 网上最近流传的一个笑话,关于兔子,狼还有一只老虎的,故事 我就是想打你了,还需要什么理由吗?谁让你是兔子 项目经理是这样当的

    程序员,不要让自己做兔子(updated) 前段时间和一个朋友聊天,酒席间向我抱怨他那段时间的郁闷:项目经理从客户那里拿来一个需求,实际上就是一个ppt描述,我这个朋友拿过来看后刚开始不觉得什么,一个 ...

  3. C语言学习笔记 (002) - C++中引用和指针的区别(转载)

    下面用通俗易懂的话来概述一下: 指针-对于一个类型T,T*就是指向T的指针类型,也即一个T*类型的变量能够保存一个T对象的地址,而类型T是可以加一些限定词的,如const.volatile等等.见下图 ...

  4. HDU 4324 Triangle LOVE (拓扑排序)

    Triangle LOVE Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Tot ...

  5. FluentScheduler

    The job configuration is handled in a Registry class. A job is either an Action or a class that inhe ...

  6. Web压力架构

    原文地址:https://www.cnblogs.com/lori/archive/2015/03/27/4370827.html Web压力架构... 1 一 系统性能测试概述... 1 1.1 性 ...

  7. 黑客公布2012年最弱智密码Top25(转)

    尽管弱密码对安全性的危害大家都知道,但是仍然有很多网民使用超弱密码.日前,黑客公布了一份密码文档,列出了今年最弱智密码. 根据 SplashData 公布的“年度最弱智密码 Top25”,和去年一样, ...

  8. android 4.x环境搭建

    一.Android搭建开发环境 (一).工具准备 原文地址:http://www.open-open.com/lib/view/open1386252535564.html 1.下载JDK JDK即J ...

  9. Python读文本文件

    file_object = open('thefile.txt') try: all_the_text = file_object.read() finally: file_object.close( ...

  10. vc2010 属性值无效 灾难性故障 解决方法

    原文链接: http://blog.csdn.net/enterlly/article/details/8739281 说明: 我遇到这个问题是这样的,在为某个类添加消息时出现的.因为该类不在此工程的 ...