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: dp.

 

 1 class Solution {
 2 public:
 3     int numDistinct(string S, string T) {
 4         int N = S.size(), M = T.size();
 5         int dp[M+1][N+1];
 6         dp[0][0] = 1;
 7         for (int j = 1; j <= N; ++j)
 8             dp[0][j] = 1;
 9         for (int i = 1; i <= M; ++i)
10             dp[i][0] = 0;
11 
12         for (int i = 1; i <= M; ++i)
13             for (int j = 1; j <= N; ++j)
14                 if (S[j-1] == T[i-1])
15                     dp[i][j] = dp[i][j-1] + dp[i-1][j-1];
16                 else
17                     dp[i][j] = dp[i][j-1];
18 
19         return dp[M][N];
20     }
21 };

 

posted @ 2014-04-24 02:24  beehard  阅读(139)  评论(0编辑  收藏  举报