/*
115. Distinct Subsequences
Total Accepted: 59855
Total Submissions: 198263
Difficulty: Hard
Contributors: Admin
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.
Hide Tags Dynamic Programming String
*/
public class NumDistinct {
public static void main(String[] args) {
String s = "rabbbit";
String t = "rabbit";
NumDistinct nd = new NumDistinct();
System.out.println(nd.numDistinct(s,t));
}
// http://blog.csdn.net/fly_yr/article/details/50408457
public int numDistinct(String s, String t) {
if (s == null || s.length() == 0 || t == null || t.length() == 0) {
return 0;
}
int lens = s.length();
int lent = t.length();
int[][] dp = new int[lens + 1][lent + 1];
dp[0][0] = 1; // s(0, i) -> t(0) 的方法数为1
for (int i = 1; i <= lens; i++) {
dp[i][0] = 1;
for (int j = 1; j <= lent; j++) {
dp[i][j] = dp[i-1][j];
if (s.charAt(i -1 ) == t.charAt(j -1)) {
dp[i][j] += dp[i-1][j-1];
}
}
}
return dp[lens][lent];
}
}
115. Distinct Subsequences
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- "求S有多少个不同的子串与T相同"count the number of distinct subsequence...
- Distinct Subsequences 这道题的题意要仔细理解。。http://blog.csdn.net/f...
- Given a string S and a string T, count the number of dist...
- Given a string S and a string T, count the number of dist...
- 问题 Given a string S and a string T, count the number of d...