Distinct Subsequences

来源:互联网 发布:阿里云搭ss加速校园网 编辑:程序博客网 时间:2024/06/04 01:28

Given a string S and a string T, count the number of distinct subsequences ofT 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.

 

DP[i][j]表示S[0,i]中有多少个T[0,j];

 

class Solution {public:    int numDistinct(string S, string T) {        if(!S.size() || !T.size())return 0;//"" 和非空串不匹配int slen = S.size();int tlen = T.size();vector<vector<int> >dp;vector<int>v;for(int i = 0; i<= slen; i++){v.clear();for(int j = 0; j <= tlen; j++)v.push_back(0);dp.push_back(v);}//"" 和"" 也是匹配dp[0][0] = 1;for(int i = 0; i <= slen; i++){for(int j = 0; j <= tlen; j++){//所有 S[0,i-1]中匹配T[0,j]的if(i)dp[i][j] += dp[i - 1][j];//若S[i - 1] == T[j - 1]则匹配数为 dp[i - 1][j - 1],在长度为j - 1的基础上长度加1if(i && j)dp[i][j] +=  S[i - 1] == T[j - 1] ? dp[i - 1][j - 1] : 0;}}return dp[slen][tlen];    }};


 

0 0
原创粉丝点击