Distinct Subsequences
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).
Given S = "rabbbit"
, T = "rabbit"
, return 3
.
递归:
if (S.charAt(indexS) == T.charAt(indexT)) {
return numDistinct(S, indexS + 1, T, indexT + 1) + numDistinct(S, indexS + 1, T, indexT);
} else {
return numDistinct(S, indexS + 1, T, indexT);
}
DP:
if (S.charAt(i - 1) == T.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] (不考虑S中第i + 1个字符);
} else {
dp[i][j] = dp[i - 1][j];
}
1 public class Solution { 2 /** 3 * @param S, T: Two string. 4 * @return: Count the number of distinct subsequences 5 */ 6 7 /* over time 8 public int numDistinct(String S, String T) { 9 if (T == null) return 1; 10 if (S == null) return 0; 11 12 return numDistinct(S, 0, T, 0); 13 } 14 15 private int numDistinct(String S, int indexS, String T, int indexT) { 16 if (indexT >= T.length()) return 1; 17 if (indexS >= S.length()) return 0; 18 19 if (S.charAt(indexS) == T.charAt(indexT)) { 20 return numDistinct(S, indexS + 1, T, indexT + 1) + numDistinct(S, indexS + 1, T, indexT); 21 } else { 22 return numDistinct(S, indexS + 1, T, indexT); 23 } 24 } 25 */ 26 27 public int numDistinct(String S, String T) { 28 if (T == null) return 1; 29 if (S == null) return 0; 30 31 int[][] dp = new int[S.length() + 1][T.length() + 1]; 32 33 for (int i = 1; i < dp[0].length; i++) { 34 dp[0][i] = 0; 35 } 36 37 for (int i = 0; i < dp.length; i++) { 38 dp[i][0] = 1; 39 } 40 41 for (int i = 1; i < dp.length; i++) { 42 for (int j = 1; j < dp[0].length; j++) { 43 if (S.charAt(i - 1) == T.charAt(j - 1)) { 44 dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]; 45 } else { 46 dp[i][j] = dp[i - 1][j]; 47 } 48 } 49 } 50 return dp[dp.length - 1][dp[0].length - 1]; 51 } 52 }