
题目描述
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).
Here is an example:
S = “rabbbit”, T = “rabbit”
Return 3.
代码
dp[i][j]表示T[0…j-1]在S[0…i-1]中distinc subsequences的数量,则以S =”rabbbit”,T = “rabbit”为例):
1 |
r a b b b i t |
所以状态转移方程为
dp[0][0] = 1; // T和S都是空串.
dp[0][1 … S.length() - 1] = 1; // T是空串,S只有一种子序列匹配。
dp[1 … T.length() - 1][0] = 0; // S是空串,T不是空串,S没有子序列匹配。
dp[i][j] = dp[i][j - 1] + (T[i - 1] == S[j - 1] ? dp[i - 1][j - 1] : 0).1 <= i <= T.length(), 1 <= j <= S.length()
1 |
public class Solution { |




近期评论