您的位置:首页 > 产品设计 > UI/UE

LeetCode: Distinct Subsequences 解题报告

2014-12-31 18:21 405 查看

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 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;
}


View Code

总结:

大家可以在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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: