CoderJesse  
wangjiexi@CS.PKU

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.

动态规划。将“S串中前m个字母的子串中包含多少个T串中前n个字母的子串”这样的问题记为A[m][n]。 可以得到递推式 :
if(S[m-1] == T[n-1]) A[m][n] = A[m-1][n-1] + A[m-1][n];
else A[m][n] = A[m-1][n-1];
再处理边界情况即可。简单起见,用类似打表记录式的递归实现。

 1 class Solution {
 2 public:
 3     int numDistinct(string S, string T) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int **a;
 7         a = new int*[S.length()];
 8         for(int i = 0;i < S.length();i++)
 9             a[i] = new int[T.length()];
10         for(int i = 0;i < S.length();i++)
11             for(int j = 0;j < T.length();j++)
12                 a[i][j] = -1;
13         return DP(S.length()-1,T.length()-1,a,&S,&T);
14     }
15     int DP(int m,int n,int **a,string *S, string *T)
16     {
17         if(n == -1)
18             return 1;
19         else if(m == -1)
20             return 0;
21         if(m < n)
22             return 0;
23         if(a[m][n] != -1)
24             return a[m][n];
25         if(S->at(m) != T->at(n))
26         {
27             a[m][n] = DP(m-1,n,a,S,T);
28             return a[m][n];
29         }
30         else
31         {
32             a[m][n] = DP(m-1,n-1,a,S,T) + DP(m-1,n,a,S,T);
33             return a[m][n];
34         }
35     }
36 };

 

 

 

posted on 2013-02-28 12:38  CoderJesse  阅读(254)  评论(0)    收藏  举报