Distinct Subsequences

Distinct Subsequences

  Total Accepted: 4132  Total Submissions: 17739 My Submissions

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

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 二维矩阵中,第一行和第一列分别表示 T为空,和S为空,显然,当T为空时,总是为1。 而S为空时,只有T为空才为1,其他均为0.

解决好第一行和第一列之后,就可以开始build optimum solution了。

拿 DP[3][4]来说吧,我们要求的是T中的rab在S=rabbbit中的最优解。

首先,T的'b' 和 S的'b' 匹配。

然后我们这里有两种选择,一种是选DP[3][4]为匹配,另一种是不选DP[3][4]为匹配而继续。

显然,DP[3][4]的结果应该是选或者不选这两种结果的和。

如果选,那么应该是DP[3-1][4-1] = DP[2][3] 这个最优解,

如果不选,那么应该是DP[3][4-1] = DP[3][3] 这个解,因为即使不匹配,也应该至少有前面已经匹配的解。这里是T中的rab已经和S中的rab匹配了,解是1,那么在DP[3][4]即便不匹配,那么也至少是1

最后把两个解相加,得出2.


如果用递归求解,那么递归式就是:

if (T.charAt(i- 1 ) == S.charAt(j- 1 )){
     memo[i][j] = memo[i][j- 1 ] + memo[i- 1 ][j- 1 ];  //不选 + 选
} else {
     memo[i][j] = memo[i][j- 1 ];  // 至少是前面的解
}

 


//recursive DP
    public static int numDistinct(String S, String T) {
        int[][] dp = new int[S.length()][T.length()];
        for (int i = 0; i < dp.length; i++) {
            for (int j = 0; j < dp[0].length; j++) {
                dp[i][j] = -1;
            }
        }
        return numDistinctHelper(S, T, 0, 0, dp);
    }

    private static int numDistinctHelper(String S, String T, int i, int j, int[][] dp) {
        if (j == T.length()) return 1;
        if (i == S.length()) return 0;
        if (dp[i][j] != -1) return dp[i][j];
        int count = 0;
        if (S.charAt(i) == T.charAt(j))
            count = numDistinctHelper(S, T, i + 1, j, dp) + numDistinctHelper(S, T, i + 1, j + 1, dp);
        else count = numDistinctHelper(S, T, i + 1, j, dp);
        dp[i][j] = count;
        return count;
    }

    // iterator DP solution
    public static int numDistinct2(String S, String T){
        int[][] memo = new int[T.length()+1][S.length()+1];
        for(int i = 0; i < S.length()+1; i++){
            memo[0][i] = 1;
        }
        for(int i =1 ; i < T.length()+1; i++){
            for(int j = 1; j < S.length()+1; j++){
                if(T.charAt(i-1) == S.charAt(j-1)){
                    memo[i][j] = memo[i][j-1] + memo[i-1][j-1];
                }else{
                    memo[i][j] = memo[i][j-1];
                }
            }
        }
        //System.out.println(Arrays.deepToString(memo));
        return memo[T.length()][S.length()];
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值