思路:直接搜索的话会有大量重复的运算,用记忆化数组记录之前的结果。当匹配到第一个串的第i位和第二个串的第j位时,前面可能有多种情况,但三个串后面的长度一定,所以结果也可以确定,用vis[i][j]记录当前状态是否匹配过 。(觉得记忆化搜索比dp可爱好多!)
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
string str1,str2,str;
bool pos;
bool vis[210][210];
int n;
void dfs(int s1, int s2, int s)
{
if(s1 == str1.length() && s2 == str2.length())
{
pos = true;
return;
}
if(str1[s1] != str[s] && str2[s2] != str[s])
return;
if(vis[s1][s2]) return;
vis[s1][s2] = 1;
if(str1[s1] == str[s]) dfs(s1 + 1, s2, s + 1);
if(str2[s2] == str[s]) dfs(s1, s2 + 1, s + 1); //WA point: can't be if...else, because may occur the head letter are the same
}
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> str1 >> str2 >> str;
memset(vis, 0, sizeof(vis));
pos = false;
dfs(0, 0, 0);
printf("Data set %d: ", i);
if(pos == true)
printf("yes\n");
else
printf("no\n");
}
return 0;
}