Title:
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 be formed from the original strings by deleting some (can B e 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 are an example:
S = "rabbbit" , T ="rabbit"
Return 3 .
Test Instructions:
Given a string s and a string t , count the number of times t as a subsequence of S.
A subsequence of the string defined here refers to the deletion of some (can be 0) characters in the original string, while preserving the original relative alphabetic order. (For example, "ACE" is a subsequence of "ABCDE" and "AEC" is not )
Here is an example:
S = "rabbbit" , T ="rabbit"
Return 3 .
Algorithm Analysis:
DP Dynamic Programming
First, set the dynamic Plan array Dp[i][j], which represents the number of sub-sequences in the S string from the start position to position I and the T string from the start position to the exact J position.
If the S string is empty, then Dp[0][j] is 0;
If the T string is empty, then dp[i][j] is 1 because the empty string is a string of any strings.
If the first character of S is different from the J character of T, then the number of sequences of res[i][j] should be the same as the number of res[i-1][j];
If the first character of S is the same as the J character of T, then the number of res[i-1][j] should be considered in addition to the number of res[i-1][j-1].
Therefore, the recursive definition is as follows:
if (S.charat (i) ==t.charat (j))
RES[I][J]=RES[I-1][J-1]+RES[I-1][J];
else Res[i][j]=res[i-1][j];
AC Code:
public class Solution {public int numdistinct (string S, String T) { //Use dynamic planning idea, define maintenance amount Res[i][j]: Represents the first I element of S and the first J elements of T can match the conversion mode int[][] res = new Int[s.length () + 1][t.length () + 1]; Res[0][0] = 1;//initial //initializes the for (int j = 1; J <= T.length (), j + +)//s is empty res[0][j] = 0; for (int i = 1; I <= s.length (), i++)//t is empty res[i][0] = 1; for (int i=1;i<s.length () +1;i++) {for (int j=1;j<t.length () +1;j++) { if (S.charat (i-1) = = T.charat (j-1)) res[i][j]=res[i-1][j-1]+res[i-1][j]; else res[i][j]=res[i-1][j]; } } Return Res[s.length ()][t.length ()];}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Distinct subsequences