Distinct Subsequences
https://leetcode.com/problems/distinct-subsequences/
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:
Example 2:
Thoughts
找S中等于T的subsequence数目。subseq match想DP。action为是否让当前的S[i -1] match T[j - 1]。dp[i, j]代表S前i和T前j个有多少个匹配的子序列。dp[i][j]至少有dp[i-1][j]个,如果让S[i- 1] match T[j - 1]还有额外dp[i-1][j-1]个。由于只与上一层有关,可以只用一维空间。
Code
Analysis
TC: O(mn)
Last updated
Was this helpful?