[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"

Return3.

题意:给定两个字符串,字符串S中能有几个T的字符串。字符串是不改变字符的相对位置,只是删减S中一部分字符,形成T,返回删减方式的种类。

思路:动态规划。维护一个二维数组dp[T.size()+1][S.size()+1],其中dp[i][j],表示T中[0,i-1]区间的子字符串和S中[0,j-1]匹配的个数.这里要注意的是,二维数组的下标和T、S中下标的对应关系,二维数组的比字符串中在左侧和上侧多一行和一列,多得为T和S中有一个为空字符串时的情况。以S ="rabbbit", T ="rabbit"得出相应的dp数组,如下:

得出状态转移方程为:dp[i][j]=dp[i][j-1]+(T[i-1]==S[j-1]?dp[i-1][j-1]:0);  (注意字符串和数组之间的下标转换),所以整体的思路是,先赋值第一行和第一列,然后由状态方程得出其他值,代码如下:

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

网友Code Gander只使用一个一维数组便实现了这个过程。代码如下:

 1 class Solution {
 2 public:
 3     int numDistinct(string S, string T) 
 4     {
 5         if(T.size()==0) return 1;
 6         if(S.size()==0) return 0;
 7 
 8        vector<int> dp(T.size()+1,0);
 9         dp[0]=1;
10 
11         for(int i=0;i<S.size()+1;++i)
12         {
13             for(int j=T.size()-1;j>=0;j--)
14             {
15                 dp[j+1]=(S[i]==T[j]?dp[j]:0)+dp[j+1];
16             }
17         }
18         return dp[T.size()];
19     }
20 };
原文地址:https://www.cnblogs.com/love-yh/p/7117816.html