Distinct Subsequences

来源:互联网 发布:c语言 获取时间毫秒 编辑:程序博客网 时间:2024/05/18 12:37

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) {    // Start typing your C/C++ solution below// DO NOT write int main() functionmap<char, bool> t_map;int n = S.size();int m = T.size();if(n < m) return 0;string s;for(int i = 0; i< m; ++i){t_map[T[i]] = true;}for(int i = 0; i< n; ++i){if(t_map.find(S[i]) != t_map.end()){s += S[i];}}n = s.size();if(n < m) return 0;int count = 0;        vector<vector<int> > res(n, vector<int>(m, 0));        int temp = 0;        if(s[0] == T[0]) res[0][0] = 1;        for(int i = 1; i< n; ++i){            if(s[i] == T[0]){                res[i][0] = res[i-1][0] + 1;            }            else{                res[i][0] = res[i-1][0];            }        }        for(int i = 1; i< n; ++i){            for(int j = 1; j < m && j <= i; ++j){                if(s[i] == T[j]){                    res[i][j] = res[i-1][j] + res[i-1][j-1];                }                else{                    res[i][j] = res[i-1][j];                }            }        }        return res[n-1][m-1];        }};


原创粉丝点击