您的位置:首页 > 产品设计 > UI/UE

leetcode: Distinct Subsequences

2014-09-03 00:01 507 查看
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
.

class Solution {
public:
int numDistinct(string S, string T) {

if (S.size() == 0 || T.size() == 0)
return 0;

int m = S.size();
int n = T.size();

vector<vector<int> > auxVtr(n+1, vector<int>(m+1));

for (int i=0; i<=n; i++)
{
for (int j=0; j<=m; j++)
{
auxVtr[i][j] = 0;
}
}

// "" substring is also the subset of S
for (int j=0; j<=m; j++)
auxVtr[0][j] = 1;

for (int i=1; i<=n; i++)
{
for (int j=1; j<=m; j++)
{
/*
*   to understand this logic
*   for example  S=ABCC; T=BC
*   When compare to S's last character 'C'
*   a(S'=ABC  T'=B  aux = 1)  b(S"=ABC  T"=BC  aux = 1)
*   if S' last character is not 'C', the result would be b
*   but now, S' last character is 'C', b is the same as above, but we need add a in this scenario
*/
if (T[i-1] == S[j-1])
{
auxVtr[i][j] = auxVtr[i-1][j-1]+auxVtr[i][j-1];
}
else
{
auxVtr[i][j] = auxVtr[i][j-1];
}
}
}

return auxVtr
[m];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: