LeetCode: 115. Distinct Subsequences
LeetCode: 115. 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).
Here is an example:
S = "rabbbit"
, T = "rabbit"
Return 3
.
题目大意: 给定 S 串和 T 串,求出 S 串中有多少个子序列等于 T 串。
解题思路 —— 动态规划
- 记:
distinctSeqNum[i][j]
为 S 串的前 i 个字符的子串中等于 T 的前 j 个字符的情况数 - 初始化:
distinctSeqNum[0...n][0] = 1
(S 串总是能生成空序列),distinctSeqNum[0][1...n] = 0
(空串总是无法 T 串序列)。 - 如果
S[i] != T[j]
, 那么 S 串的前 i 个字符的子串中等于 T 的前 j 个字符的情况数就和S串不要第 i 个字符的情况一样。 即,distinctSeqNum[i][j] = distinctSeqNum[i-1][j]
。 - 如果
S[i] == T[j]
, 那么生成 T 的子序列不要 S 的第 i 个字符,则distinctSeqNum[i][j] = distinctSeqNum[i-1][j]
。 如果生成 T 的子序列要 S 的第 i 个字符,则,distinctSeqNum[i][j] = distinctSeqNum[i-1][j-1]
。综上,distinctSeqNum[i][j] = distinctSeqNum[i-1][j] + distinctSeqNum[i-1][j-1]
。
AC 代码
class Solution {
public:
int numDistinct(string s, string t) {
// distinctSeqNum[i][j]: s 串的前 i 个字符的子串中等于 t 的前j个字符的情况数
vector<vector<int>> distinctSeqNum;
// initializing...
distinctSeqNum.resize(s.size()+1, vector<int>(t.size()+1, 0));
for(int i = 0; i <= s.size(); ++i)
{
distinctSeqNum[i][0] = 1;
}
for(size_t i = 0; i < s.size(); ++i)
{
for(size_t j = 0; j < t.size(); ++j)
{
if(j > i) break;
if(s[i] == t[j])
{
distinctSeqNum[i+1][j+1] = distinctSeqNum[i][j] + distinctSeqNum[i][j+1];
}
else
{
distinctSeqNum[i+1][j+1] = distinctSeqNum[i][j+1];
}
}
}
return distinctSeqNum[s.size()][t.size()];
}
};