LeetCode Distinct Subsequences

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.

思路分析:首先引用一个经验总结“When you see string problem that is about subsequence or matching, dynamic programming method should come to your mind naturally.” 这类题目可以看作字符串编辑距离的变形题目,这题的题意是我们只能进行删除操作,有多少做方法可以把S变成T。显然可以用动态规划做,令S与T的长度是m和n,我们定义二维数组dp[m+1][n+1] 表示把S的前m个变成T的前n个的方法数,我们在最前面增加了一维对应空字符串,初始化如下

dp[0][0] = 1//当S与T都是空时,有一种方法,不做任何删除即可

dp[0][1 ... n] = 0//当S是空但是T不是空时,没有方案

dp[1...m][0] = 1 //当T是空时,从S变成T只有一种方法,就是删除所有字符

接下来我们来想递推方程。当S[i]!=T[j]时 dp[i][j] = dp[i-1][j],因为此时我们只能把S前i-1个变成T的前j个,然后删除掉S[i]既可达到目的,因此有dp[i-1][j]种方法;当S[i]=T[j]时,显然上面的方法仍然可行,同时我们多了一种方法,就是把S的前i-1个变成T的前j-1个,然后加上后面相等的字符自然可以匹配上,因此这时dp[i][j] = dp[i-1][j] + dp[i-1][j-1]。综上所述我们有

dp[i][j] = dp[i-1][j] + (S.charAt(i-1) == T.charAt(j-1) ? dp[i-1][j-1] : 0)

有了递推方程,解决这题就变成二维数组填表了,很容易解决。这类字符串匹配题目还有很多,可以联系编辑距离那道题来想,很多都可以用动态规划解决。最后引用一个经典的示意图,显示了题目中例子的计算过程,但是注意这个例子中行列的定义和我相反,图中行对应T,列对应S,要加以区分,但是计算过程是相同的。来源 http://blog.csdn.net/abcbc/article/details/8978146

   r a b b b i t

  1 1 1 1 1 1 1 1

0 1 1 1 1 1 1 1

a 0 1 1 1 1

b 0 0 2 3 3 3

b 0 0 0 0 3 3 3

i 0 0 0 0 0 0 3 3

t 0 0 0 0 0 0 0 3  

AC Code

public class Solution {
    public int numDistinct(String S, String T) {
        //varations of edit distance problems
        //you can only delete chars to change S to T
        //if(S.isEmpty()) return 0;
        //if(T.isEmpty()) return 1;
        int m = S.length();
        int n = T.length();
        int [][] dp = new int[m + 1][n + 1];
        dp[0][0] = 1;
        for(int i = 1; i <= m; i++){
            dp[i][0] = 1;
        }
        for(int i = 1; i <= n; i++){
            dp[0][i] = 0;
        }
        for(int i = 1; i <= m; i++){
            for(int j = 1; j <= n; j++){
                dp[i][j] = dp[i-1][j] + (S.charAt(i-1) == T.charAt(j-1) ? dp[i-1][j-1] : 0);
            }
        }
        return dp[m][n];
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值