1. 程式人生 > >LintCode -- 不同的子序列

LintCode -- 不同的子序列

LintCode -- 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>