[LeetCode] 115. Distinct Subsequences

来源:互联网 发布:.net域名 编辑:程序博客网 时间:2024/06/05 15:06

难度等级:hard

题目:

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.

题解:又是一道dp问题。

  状态定义:dp[i][j]代表s[0~i-1]中T[0~j-1]不同子串的个数。
  递推关系式:S[i-1]!= T[j-1]:  DP[i][j] = DP[i-1][j] (不选择S中的s[i-1]字符)
                          S[i-1]==T[j-1]: DP[i][j] = DP[i-1][j-1](选择S中的s[i-1]字符) + DP[i-1][j]
  初始状态:第0列:DP[i][0] = 1,第0行:DP[0][j] = 0

代码:

class Solution {
public:
    int numDistinct(string S, string T) {
        int n=S.size();
        int m=T.size();
        int dp[n+1][m+1];
        
        for(int i=0;i<=n;i++)
            dp[i][0]=1;


        for(int j=1;j<=m;j++)
            dp[0][j]=0;
        
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++){
                if(S[i-1]==T[j-1])
                    dp[i][j]=dp[i-1][j]+dp[i-1][j-1];
                else
                    dp[i][j]=dp[i-1][j];
            }
        return dp[n][m];
    }
};