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 was formed from the original string by deleting some (can be none) of the C Haracters without disturbing the relative positions of the remaining characters. (ie, is a subsequence of and is not "ACE"
"ABCDE"
"AEC"
).
Here are an example:
S = "rabbbit"
, T ="rabbit"
Return 3
.
This type of dynamic programming topic is initialization + State transfer. Practice more.
Public classSolution { Public intnumdistinct (string s, String t) {intm=s.length (); intn=t.length (); intdp[][]=New int[M+1] [N+1]; dp[0][0]=1; for(inti=1;i<m;i++) {dp[i][0]=1; } for(intj=1;j<n;j++) {dp[0][j]=0; } for(inti=1;i<=m;i++) for(intj=1;j<=n;j++){ if(S.charat (i-1) ==t.charat (j-1)) Dp[i][j]=dp[i-1][j]+dp[i-1][j-1]; ElseDp[i][j]=dp[i-1][j]; } returnDp[m][n]; }}
View Code
Leetcode 115:distinct Sequence