115.Distinct Subsequences 求相同子序列数 Tag:DP, string


题目描述:

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.


参考答案1:

     利用递归的思路。假设当前输入串分别为 s_tmp, t_tmp, 目的是求s_tmp的不同子序列中t_tmp出现的个数。先利用for循环寻找s_tmp串中第一个与t_tmp[0]对应的字符,从而确定了输入递归函数的新的s_tmp,t_tmp。

    不过这种方法在LeetCode上会TLE, 仅供参考。

class Solution {
public:
    int numDistinct(string s, string t) {
        if(s.size() < t.size()) return 0;
        if(t.size() == 0)   return 1;
        
        int num = 0;//可能数
        for(int i = 0;i < s.size();i++)//寻找初始对应点,有可能是多个
        {
            if(s[i] == t[0])//i开始对应
            {
                string s_tmp = s.substr(i+1);
                string t_tmp = t.substr(1);
                num += numDistinct(s_tmp, t_tmp);
            }
        }
        return num;
    }
};

参考答案2:

     利用DP动态规划的思路。定义table[i][j]为s[0:i]的不同子序列中t[0:j]出现的个数,那么按照如下方式构建table表:

初始化:table[i][0] = 1,for i ∈ [0,s.size())

如果  s[i] != t[j]:    table[i][j] = table[i - 1][j];

如果  s[i] == t[j]:    分s[i]与t[j]是否配对两种情况,则 table[i][j] = table[i-1][j] + table[i-1][j-1]

int numDistinct(string s, string t) {
        if(s.size() < t.size()) return 0;
        if(t.size() == 0)   return 1;
        
        int const M = s.size();
        int const N = t.size();
        
        vector<vector<int>> table(M + 1,vector<int>(N + 1,0));
        for(int i = 0;i < M;i++)
        {
            table[i][0] = 1;
        }
        for(int i = 0;i < M ;i++)
        {
            for(int j = 0;j < N ;j++)
            {
                if(s[i] == t[j])
                {
                    table[i+1][j+1] = table[i][j+1] + table[i][j];
                }
                else
                {
                    table[i+1][j+1] = table[i][j+1];
                }
            }
        }
        return table[M][N];
    }

 





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章