LintCode -- 不同的子序列

来源:互联网 发布:潘石屹三段婚姻知乎 编辑:程序博客网 时间:2024/05/19 02:20

LintCode -- distinct-subsequences(不同的子序列)


原题链接:http://www.lintcode.com/zh-cn/problem/distinct-subsequences/


给出字符串S和字符串T,计算S的不同的子序列中T出现的个数。

子序列字符串是原始字符串通过删除一些(或零个)产生的一个新的字符串,并且对剩下的字符的相对位置没有影响。(比如,“ACE”“ABCDE”的子序列字符串,而“AEC”不是)。 

样例

给出S = "rabbbit", T = "rabbit"

返回 3


分析:

dp[ i ][ j ] 表示 T 有 j 个字符,S有 i 个字符时不同子序列个数。

递归式 if (T[ i ] == S[ j ]) dp[ i ][ j ] = dp[ i ][ j-1 ] + dp[ i-1 ][ j-1 ]

           else dp[ i ][ j ] = dp[ i ][ j-1 ]

**** 时间复杂度 O(n*m), 空间复杂度 O(m) ****


代码(C++、Java、Python):

<span style="font-size:18px;">class Solution {public:        /**     * @param S, T: Two string.     * @return: Count the number of distinct subsequences     */    int numDistinct(string &S, string &T) {        // write your code here        int n = S.size();        int m = T.size();        int dp[m+1][2];        memset(dp, 0, sizeof(dp));        for (int j = 0; j < 2; j++)            dp[0][j] = 1;        for (int j = 1; j < n+1; j++)            for (int i = 1; i < m+1; i++){                dp[i][j%2] = dp[i][(j-1)%2];                if (T[i-1] == S[j-1])                    dp[i][j%2] += dp[i-1][(j-1)%2];            }        return dp[m][n%2];    }};</span>

<span style="font-size:18px;">public class Solution {    /**     * @param S, T: Two string.     * @return: Count the number of distinct subsequences     */    public int numDistinct(String S, String T) {        // write your code here        int n = S.length();        int m = T.length();        int [][] dp = new int [m+1][2];        for (int j = 0; j < 2; j++)            dp[0][j] = 1;        for (int j = 1; j < n+1; j++)            for (int i = 1; i < m+1; i++){                dp[i][j%2] = dp[i][(j-1)%2];                if (T.charAt(i-1) == S.charAt(j-1))                    dp[i][j%2] += dp[i-1][(j-1)%2];            }        return dp[m][n%2];    }}</span>

<span style="font-size:18px;">class Solution:     # @param S, T: Two string.    # @return: Count the number of distinct subsequences    def numDistinct(self, S, T):        # write your code here        n = len(S)        m = len(T)        dp = [[0 for j in range(2)] for i in range(m+1)]        for j in range(2):            dp[0][j] = 1        for j in range(1, n+1):                for i in range(1, m+1):                dp[i][j%2] = dp[i][(j-1)%2]                if T[i-1] == S[j-1]:                    dp[i][j%2] += dp[i-1][(j-1)%2]        return dp[m][n%2]</span>


0 0
原创粉丝点击