【leetcode】Distinct Subsequences(hard)

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"

意思是指可以通过多少种方式删除S的一部分字母使得S变为T。

思路:真高兴,又做出来了~~

用ways[m][n]存储 S[0~m-1]变为T[0~n-1]的方式

那么  ways[i][j] = ways[i-1][j] //扔掉S[i-1] 

                     +((S[i-1] == T[j-1]) ? ways[i-1][j-1] : 0); //当前S与T的字母匹配,则需加上S[0~m-2]变为T[0~n-2]的方式数

class Solution {
public:
    int numDistinct(string S, string T) {
        int slen = S.length();
        int tlen = T.length();

        if(slen < tlen) return 0;

        vector<vector<int>> ways(slen + 1, vector<int>(tlen + 1, 0));
        ways[0][0] = 1;
        for(int i = 1; i < slen + 1; i++)
        {
            ways[i][0] = 1; //若T没有字母那么只有一种方式令S变为T:删除S全部的字母
        }
        for(int i = 1; i < slen + 1; i++)
        {
            for(int j = 1; j < tlen + 1; j++)
            {
                ways[i][j] = ways[i-1][j]  //扔掉当前的 
                             +((S[i-1] == T[j-1]) ? ways[i-1][j-1] : 0); //当前S与T的字母匹配
            }
        }
        return ways[slen][tlen];
    }
};

看了看别人的答案,发现我们的代码几乎是一模一样,难道说题做多了大家的风格都一样了吗?

有个优化的方法,因为在计算ways[i][j]时,只用到了ways[i-1]行的信息,所以没有必要存储所有的历史信息,只要存上一行的就好。

/**
 * Further optimization could be made that we can use only 1D array instead of a
 * matrix, since we only need data from last time step.
 */

int numDistinct(string S, string T) {
    int m = T.length();
    int n = S.length();
    if (m > n) return 0;    // impossible for subsequence

    vector<int> path(m+1, 0);
    path[0] = 1;            // initial condition

    for (int j = 1; j <= n; j++) {
        // traversing backwards so we are using path[i-1] from last time step
        for (int i = m; i >= 1; i--) {  
            path[i] = path[i] + (T[i-1] == S[j-1] ? path[i-1] : 0);
        }
    }

    return path[m];
}
原文地址:https://www.cnblogs.com/dplearning/p/4181832.html