题目描述:
Given a string S and a string T, count the number of distinct subsequences ofT inS.
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).
Here is an example:
S = "rabbbit"
, T = "rabbit"
Return 3
.
简单翻译一下,给定两个字符串S和T,求S有多少个不同的子串与T相同。S的子串定义为在S中任意去掉0个或者多个字符形成的串。
递归求解:
首先找到在S中与T的第一个字符相同的字符,从这个字符开始,递归地求S和T剩下的串。T为空串时,返回1。因为空串本身是另外一个串的一个子序列。这个算法实现简单,但是果然不出意料,大集合超时。
Java代码: