[LeetCode-115] 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.

 

一开始历遍,妥妥的超时,后来用了DP……代码说话吧……

 

 1 class Solution {
 2     public:
 3 
 4         /* 妥妥的太慢
 5         void tryStr(string str, const string& T, int & result) {
 6             if (str.length() < T.length()) {
 7                 return;
 8             }
 9             else if (str.length() > T.length()) {
10                 tryStr(str.substr(0, i) + str.substr(i + 1, str.length() - i), T, result);
11             }
12             else if (0 == str.compare(T)) {
13                 ++result;
14             }
15         }
16         int numDistinct(string S, string T) {
17             // Start typing your C/C++ solution below
18             // DO NOT write int main() function
19             int result = 0;
20             tryStr(S, T, result);
21             return result;
22         }
23         */
24 
25         int numDistinct(string S, string T) {
26             // Start typing your C/C++ solution below
27             // DO NOT write int main() function
28             int slen = S.length();
29             int tlen = T.length();
30             if (tlen > slen)
31             {
32                 return 0;
33             }
34             int **dp = new int*[tlen];
35             for (int i = 0; i < tlen; ++i)
36             {
37                 dp[i] = new int[slen];
38                 memset(dp[i], 0, slen * sizeof(int));
39             }
40             dp[0][0] = ((S[0] == T[0]) ? 1 : 0);
41             for (int j = 1; j < slen; ++j)
42             {
43                 dp[0][j] = dp[0][j - 1] + ((T[0] == S[j]) ? 1 : 0);
44             }
45             for (int i = 1; i < tlen; ++i)
46             {
47                 for (int j = 1; j < slen; ++j)
48                 {
49                     dp[i][j] = dp[i][j - 1] + ((T[i] == S[j]) ? dp[i - 1][j - 1] : 0);
50                 }
51             }
52 
53             int result = dp[tlen - 1][slen - 1];
54             for (int i = 0; i < tlen; ++i)
55             {
56                 delete [] dp[i];
57             }
58             delete [] dp;
59             return result;
60         }
61 };
View Code

 

转载于:https://www.cnblogs.com/leon-wang/p/3275735.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值