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).
Here is an example:
S = "rabbbit"
, T = "rabbit"
Return 3
.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public int numDistinct(String S, String T) { 3 int len1 =S.length(); 4 int len2 = T.length(); 5 int[][] dp = new int [len1+1][len2+1]; 6 for(int i=0;i<=len2;i++){ 7 dp[0][i] = 0; 8 } 9 for(int i=0;i<=len1;i++){ 10 dp[i][0] = 1; 11 } 12 for(int i=1;i<=len1;i++){ 13 for(int j=1;j<=len2;j++){ 14 if(S.charAt(i-1)!=T.charAt(j-1)) 15 dp[i][j] = dp[i-1][j]; 16 else 17 dp[i][j] = dp[i-1][j] + dp[i-1][j-1]; 18 } 19 } 20 return dp[len1][len2]; 21 } 22 }