Description: 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).
Example: Given S = “rabbbit”, T = “rabbit”, return 3.
分析:
动态规划,关键是如何得到递推关系,可以这样想:设母串的长度为 j,子串的长度为 i,我们要求的就是长度为 i 的子串在长度为 j 的母串中出现的次数,设为dp[i][j]。可以分为下面两种情况: