# 【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.

class Solution {
public:
int numDistinct(string S, string T) {
return count(S,T,0,0);
}

int count(string s,string t,int pos1,int pos2)
{
if(pos2==t.size())
return 1;
if(pos1==s.size())
return 0;
int sum=0;
for(unsigned int i=pos1;i<s.size();i++)
{
if(s[i]==t[pos2])
{
sum+=count(s,t,i+1,pos2+1);
}
}
return sum;
}
};

1）设母串长度为i，子串长度为j，当s[i]==t[j]时，则dp[i][j]=dp[i-1][j]+dp[i-1][j-1]。当s[i]!=t[j]时，dp[i][j]=dp[i-1][j]。

2）设母串子串的长度分别为a,b。则dp的数组大小应该是(a+1)*(b+1)，其中包括空字符串“”的情况。

3）数组中的dp[i][j]实际上比较的是s[i-1]与t[j-1]是否相等的情况。

4）需将dp的第一列数字置1，除dp[0][0]外的第一行置0.

class Solution {
public:
int numDistinct(string S, string T) {
return count2(S,T);
}

int count2(string s,string t)
{
unsigned int a=s.size(),b=t.size();
int **dp=new int*[a+1];
for(unsigned int i=0;i<=a;i++)
{
dp[i]=new int[b+1];
memset(dp[i],0,b+1);
}
for(unsigned int i=0;i<=a;i++)
{
dp[i][0]=1;
}
for(unsigned int i=1;i<=b;i++)
{
dp[0][i]=0;
}
for(unsigned int i=1;i<=a;i++)
{
for(unsigned int j=1;j<=b;j++)
{
if(s[i-1]==t[j-1])
{
dp[i][j]=dp[i-1][j]+dp[i-1][j-1];
}
else
{
dp[i][j]=dp[i-1][j];
}
}
}
return dp[a][b];
}
};

## LeetCode115 Distinct Subsequences

• zxwtry
• 2017年05月01日 20:44
• 117

## leetcode Distinct Subsequences

Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequen...

## Leetcode:Distinct Subsequences

Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequen...

## Leetcode Distinct Subsequences 动态规划法活用总结

举报原因： 您举报文章：【Leetcode】Distinct Subsequences 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)