标签:
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
r 0 1 1 1 1 1 1 1
a 0 0 1 1 1 1 1 1
b 0 0 0 1 2 3 3 3
b 0 0 0 0 1 3 3 3
i 0 0 0 0 0 0 3 3
t 0 0 0 0 0 0 0 3
AC Codepublic 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]; } }
LeetCode Distinct Subsequences
标签:
原文地址:http://blog.csdn.net/yangliuy/article/details/43526751