題目:
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. ”
所以這種型別題可以多往DP思考思考。
首先設定動態規劃陣列dp[i][j],表示S串中從開始位置到第i位置與T串從開始位置到底j位置匹配的子序列的個數。
如果S串為空,那麼dp[0][j]都是0;
如果T串為空,那麼dp[i][j]都是1,因為空串為是任何字串的字串。
可以發現規律,dp[i][j] 至少等於 dp[i][j-1]。
當i=2,j=1時,S 為 ra,T為r,T肯定是S的子串;這時i=2,j=2時,S為ra,T為rs,T現在不是S的子串,當之前一次是子串所以現在計數為1.
同時,如果字串S[i-1]和T[j-1](dp是從1開始計數,字串是從0開始計數)匹配的話,dp[i][j]還要加上dp[i-1][j-1]
例如對於例子: S = "rabbbit"
, T = "rabbit"
當i=2,j=1時,S 為 ra,T為r,T肯定是S的子串;當i=2,j=2時,S仍為ra,T為ra,這時T也是S的子串,所以子串數在dp[2][1]基礎上加dp[1][1]。
程式碼如下:
2 int[][] dp = new int[S.length() + 1][T.length() + 1];
3 dp[0][0] = 1;//initial
4
5 for(int j = 1; j <= T.length(); j++)//S is empty
6 dp[0][j] = 0;
7
8 for (int i = 1; i <= S.length(); i++)//T is empty
9 dp[i][0] = 1;
10
11 for (int i = 1; i <= S.length(); i++) {
12 for (int j = 1; j <= T.length(); j++) {
13 dp[i][j] = dp[i - 1][j];
14 if (S.charAt(i - 1) == T.charAt(j - 1))
15 dp[i][j] += dp[i - 1][j - 1];
16 }
17 }
18
19 return dp[S.length()][T.length()];
20 }
Reference:http://blog.csdn.net/abcbc/article/details/8978146