[leetcode]Distinct Subsequences

来源:互联网 发布:visual studio c编程 编辑:程序博客网 时间:2024/04/29 23:27

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() function        int M = S.size(), N = T.size();        if(M == 0 || N == 0) return 0;                vector<vector<int>> f(M, vector<int>(N, 0));        f[0][0] = S[0] == T[0] ? 1 : 0;        for(int i = 1; i < M; i++){            if(S[i] == T[0]){                f[i][0] = f[i-1][0] + 1;            }else{                f[i][0] = f[i-1][0];            }        }                for(int i = 1; i < M; i++){            for(int j = 1; j < N; j++){                if(S[i] == T[j]){                    f[i][j] = f[i-1][j-1] + f[i-1][j];                }else{                    f[i][j] = f[i-1][j];                }            }        }                return f[M-1][N-1];            }};