LeetCode-Distinct Subsequences-唯一子序列-LCS变种DP

https://oj.leetcode.com/problems/distinct-subsequences/

首先要理解题目:count the number of distinct subsequences of T in S.

意思是,数出T在S的唯一子序列的个数。也就是有多少个S的子序列是T。子序列可以有间隔。

LCS的DP思路来做就可以了:

定义f (p,q) :S中[0,p)的子串中含T的[0,q)的个数。

其中q=0时,f(p,0)=1,这个子序列就是空序列.而p=0但q>0时f(0,q)=0,因为没有可以找出的子序列。

然后考虑f(p,q),这里的S的子序列为T有两种情况:

1)子序列包含s[p-1],这种子序列个数为f(p-1,q-1)

2) 子序列不包含s[p-1],这种子序列个数为f(p-1,q)

如此就得到DP的递推。进而可以简单求解。

class Solution {
public:
    int n,m;
    int numDistinct(string S, string T) {
        n=S.length();
        m=T.length();
        vector<vector<int>> dp(n+1,vector<int>(m+1,0));
        for(int i=0;i<=n;i++) dp[i][0]=1;
        for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) {
            dp[i][j]=dp[i-1][j];
            if(S[i-1]==T[j-1]) dp[i][j]+=dp[i-1][j-1];
        }
        return dp[n][m];
    }
};

 

posted @ 2014-10-19 00:41  zombies  阅读(236)  评论(0编辑  收藏  举报