Distinct Subsequences | Training dragons the hard way - Programming Every Day!
Problem Description Given a string S and a string T, count the number of distinct sub-sequences of T in S.
A sub-sequence 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 =
S =
"rabbbit"
, T = "rabbit"
Return
NOTE: The above problem statement is not very clear. We can make it "cleaner" by re-stating the problem as:3
.Given a string S and a string T, counting the number of ways that we remove some (or none) characters in S to get the remaining string equal to T.
Solutions
For a string str, we denote str[0,j] is the sub-string of str from index 0 to j inclusively. We easily guess that this solution can be solved by Dynamic Programming.
If we call dp[i][j] is the number of ways to remove some characters from S[0,i] to get T[0,j], we have the recursive formula:
dp [i][j] = dp[i-1][j] if S[i] != T[j] , or
dp [i][j] = dp[i-1][j] + dp[i-1][j-1] if S[i] ==T[j]
Read full article from Distinct Subsequences | Training dragons the hard way - Programming Every Day!
No comments:
Post a Comment