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。
這道題考察的是從S刪除若干字符後與T相等的方法有多少種,用dp[i][j]表示從0到i,從0到j的變換方式(刪除方法)有多少種。
參考http://www.cnblogs.com/TenosDoIt/p/3440022.html
Source
public class Solution {
public int numDistinct(String S, String T) {
int len1 = S.length(), len2 = T.length();
if(len1 == 0) return 0;
if(len2 == 0) return 1; //T爲空串,變化方式爲1,空串是任何字符串的子串
int[][] dp = new int[len1 + 1][len2 + 1];
for(int i = 0; i <= len1; i++){
dp[i][0] = 1;
}
for(int i = 1; i <= len1; i++){
for(int j = 1; j <= len2; j++){
if(S.charAt(i - 1) == T.charAt(j - 1))
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
else dp[i][j] = dp[i - 1][j]; //至少等於dp[i-1][j]
//這道題考察的是S刪除某些位置得T的方法有多少種,所以遍歷時肯定會出現當前子串不相等的情況,比如
//S=rabbb T=rabbi的這種情況 此時dp[i][j] = dp[i-1][j] 刪除方法和上一步i-1時相同
}
}
return dp[len1][len2];
}
}