392.判断子序列
题目链接:https://leetcode.cn/problems/is-subsequence/submissions/
代码(动态规划):
class Solution {
public:
bool isSubsequence(string s, string t) {
int n1 = s.size();
int n2 = t.size();
vector<vector<int>> dp(n1+1,vector<int>(n2+1,0));
for(int i = 1; i <= n1; i++)
{
for(int j = 1; j <= n2; j++)
{
if(s[i-1] == t[j-1])
{
dp[i][j] = dp[i-1][j-1]+1;
}else
{
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
}
}
if(dp[n1][n2] == n1)
return true;
else return false;
}
};
16行那里可以改成:dp[i][j] = dp[i][j-1];
因为之前的是两个都会删除然后比较,这边的话就只把t删掉,取它的前一个就行
代码二:
class Solution {
public:
bool isSubsequence(string s, string t) {
int n1 = s.size();
int n2 = t.size();
string result = "";
int j = 0;
for(int i = 0; i < n2; i++)
{
if(s[j] == t[i])
{
result += s[j];
j++;
if(j == n1)
break;
}
}
if(result == s)
return true;
else return false;
}
};
这种方法效率更好
115.不同的子序列
题目链接:https://leetcode.cn/problems/distinct-subsequences/
代码:
class Solution {
public:
int numDistinct(string s, string t) {
//dp:以i-1为结尾的s子序列中出现以j-1为结尾的t的个数为dp[i][j]。
vector<vector<uint64_t>> dp(s.size()+1,vector<uint64_t>(t.size()+1,0));
//dp[i][0]:以i-1为结尾的s子序列中出现为null的t的个数
//dp[0][i]:为null的s子序列中出现以i-1为结尾的t的个数
for(int i = 0; i <= s.size();i++)
{
dp[i][0] = 1;
}
for(int i = 1 ; i <= s.size(); i++)
{
for(int j = 1; j <= t.size(); j++)
{
if(s[i-1] == t[j-1])
dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
else
dp[i][j] = dp[i-1][j];
}
}
return dp[s.size()][t.size()];
}
};
要注意初始化
代码(回溯):
class Solution {
public:
int result = 0;
string cur = "";
void judge(string s,string t,int start_index)
{
if(cur == t)
{
result++;
return;
}
int i = 0;
while(i < cur.size())
{
if(cur[i] == t[i])
i++;
else
return;
}
if(start_index >= s.size())
return;
for(int i = start_index; i < s.size(); i++)
{
cur += s[i];
judge(s,t,i+1);
cur = cur.substr(0,cur.size()-1);
}
return;
}
int numDistinct(string s, string t) {
judge(s,t,0);
return result;
}
};
这个超时了 那个数据集很变态