Problem
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
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).
Example 1:
1 | |
Example 2:
1 | |
Explanation
-
We can use dynamic programming to solve this problem.
-
Dynamic state is a two dimensional array
dp[i][j]which represents aSis choosing characters from the beginning tojinclusive (top row), andTis choosing characters from the beginning toiinclusive (left column), the value ofdp[i][j]is their result. -
Dynamic init is, when both
TandSare empty, the result will be 1 because emptyScan form emptyT. Also actually in the top row all elements are 1 because whenTis empty, no matte how many characters we choose fromS, they can all form the empty string by choosing the empty string. On the other hand, whenSis empty, butTis not empty, thenScannot formT, so left most column values are 0. -
Dynamic function can have two cases. First, if the last characters of
TandSare the same, thendp[i][j] = dp[i-1][j-1] + dp[i][j-1]because if we don’t choose the last characters fromTandSthen it’s equal todp[i-1][j-1], and if we don’t choose the last character fromS, then it’s equal todp[i][j-1]. Second case is when the last character are not the same, so we can only don’t choose the last character fromS, so we havedp[i][j] = dp[i][j-1]. -
Dynamic result is choosing all characters from
SandT, which is the bottom right result.
Solution
1 | |