LeetCode之“动态规划”: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.

  该题解析参考自LeetCode题解

  设状态为dp[i][j],表示T[0, j]在S[0, i]里出现的次数。首先,无论S[i]和T[j]是否相等,若不使用S[i],则dp[i][j]=dp[i-1][j];若S[i]=T[j],则可以使用S[i],此时dp[i][j]=dp[i-1][j]+dp[i-1][j-1]。

  代码如下:

 1 class Solution {
 2 public:
 3     int numDistinct(string s, string t) {
 4         int szS = s.size();
 5         int szT = t.size();
 6         if(szS < szT)
 7             return 0;
 8         
 9         vector<vector<int> > dp(szS + 1, vector<int>(szT + 1, 0));
10         for(int i = 0; i < szS + 1; i++)
11             dp[i][0] = 1;
12         
13         for(int i = 1; i < szS + 1; i++)
14             for(int j = 1; j < szT + 1; j++)
15             {
16                 if(s[i-1] != t[j-1])
17                     dp[i][j] = dp[i-1][j];
18                 else
19                     dp[i][j] = dp[i-1][j] + dp[i-1][j-1];
20             }
21 
22         return dp[szS][szT];
23     }
24 };

   

posted @ 2015-06-16 17:06  峰子_仰望阳光  阅读(176)  评论(0编辑  收藏  举报