首页 > 代码库 > Leetcode: Distinct Subsequences
Leetcode: Distinct Subsequences
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
.
分析:此题题目叙述比较不明确,改为"count the number of distinct subsequence T in S", 即找到S中等于T的subsequence个数。我们可以用动态规划的方法来解。我们用record[i][j]表示S[0:i-1]中等于T[0:j-1]的subsequence个数。那么当S[i-1] == T[j-1]时,record[i][j] = record[i-1][j] + record[i-1][j-1];当S[i-1] != T[j-1]时,record[i][j] = record[i-1][j]。在实现时,可以用一个二维数组保存record,也可以用一个一维数组,二维数组的方式更容易理解。
1. 二维数组实现:
class Solution {public: int numDistinct(string S, string T) { int m = S.size(), n = T.size(); int record[m+1][n+1]; for(int i = 0; i < m+1; i++) record[i][0] = 1; for(int j = 1; j < n+1; j++) record[0][j] = 0; for(int i = 1; i < m+1; i++) for(int j = 1; j < n+1; j++){ if(S[i-1] == T[j-1]) record[i][j] = record[i-1][j-1] + record[i-1][j]; else record[i][j] = record[i-1][j]; } return record[m][n]; }};
2. 一维数组实现,我们可以用两个长度为T.length()+1的一维数组prev和cur,prev记录record[i-1][j], cur记录record[i][j],因为记录关于i的record时,只用到i-1的信息。其实我们可以更节省空间,只用一个一维数组,但要从后往前遍历j,因为要保证当前被更新的旧值不会被以后的计算用到。代码如下:
class Solution {public: int numDistinct(string S, string T) { vector<int> record(T.length()+1, 0); record[0] = 1; for(int i = 0; i < S.length(); i++) for(int j = T.length(); j > 0; j--){ if(S[i] == T[j-1]) record[j] += record[j-1]; } return record[T.length()]; }};
Leetcode: Distinct Subsequences