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: let F(i, j) denote the number of ways for S[0]…S[i] contain T[0]..T[j], Then F(n-1, m-1) is our answer and we have
if(S[i] != T[j]) F(i, j) = F(i-1, j);
if(S[i] == T[j]) F(i, j) = F(i-1, j-1) + F(i-1, j);
如果当前字符相同,那有两种可能,用到和不用到这个字符,所以这两种情况加起来。
如果不同,那只能等于用不了这个字符的情况。
1 public class Solution { 2 public int numDistinct(String S, String T) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 if(S == null || S.length() == 0){ 6 return 0; 7 } 8 9 if(T == null || T.length() == 0){ 10 return 1; 11 } 12 13 int sLen = S.length(), tLen = T.length(); 14 if(sLen < tLen){ 15 return 0; 16 } 17 18 int[][] dp = new int[sLen + 1][tLen + 1]; 19 for(int i = 0; i < sLen + 1; i++){ 20 dp[i][0] = 1; 21 } 22 23 for(int i = 1; i < tLen + 1; i++){ 24 dp[0][i] = 0; 25 } 26 27 for(int i = 1; i < sLen + 1; i++){ 28 for(int j = 1; j < tLen + 1; j++){ 29 if(S.charAt(i - 1) == T.charAt(j - 1)){ 30 dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]; 31 } else { 32 dp[i][j] = dp[i - 1][j]; 33 } 34 } 35 } 36 37 return dp[sLen][tLen]; 38 } 39 }