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];
}
}