leetcode No115. Distinct Subsequences

来源:互联网 发布:北京大兴行知学校小学 编辑:程序博客网 时间:2024/06/05 16:30

Question

Given a string S and a string T, count the number of distinct subsequences of S which equals T.

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.

Algorithm

类似编辑距离,比编辑距离简单
http://blog.csdn.net/u011391629/article/details/73047088

求把T变换成S的方法数

Accepted Code

class Solution {public:    int numDistinct(string s, string t) {        int M=s.size();        int N=t.size();        if(M < N)            return 0;        //row is t(N)    column is s(M)        vector<vector<int>> dp(N+1);        for(int i=0;i<=N;i++)            dp[i].resize(M+1);        for(int j=0;j<=M;j++)            dp[0][j]=1;        for(int i=1;i<=N;i++)            dp[i][0]=0;        for(int i=1;i<=N;i++){            for(int j=1;j<=M;j++){                if(s[j-1]==t[i-1])                    dp[i][j]=dp[i][j-1]+dp[i-1][j-1];                else                    dp[i][j]=dp[i][j-1];            }        }        return dp[N][M];    }};
原创粉丝点击