class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
if (s1.size() + s2.size() != s3.size())return false;
unordered_map<int, unordered_map<int, bool>> hashMap;
std::function<bool(int,int,int)> check = [&](int i, int j ,int k) -> bool { // 内嵌函数
if(hashMap.find(i)!=hashMap.end()) //dfs的记忆化
{
auto it =hashMap.find(i)->second;
if(it.find(j)!=it.end())
return hashMap[i][j];
}
if (k == s3.size()){ //k越界,s3扫描完了,返回true
hashMap[i][j] = true;
return true;
}
bool isValid = false;
if (i < s1.size() && s1[i] == s3[k]){
isValid = check(i+1, j, k+1);
}
if (j < s2.size() && s2[j] == s3[k]){
isValid = isValid || check(i, j+1, k+1);
}
return hashMap[i][j] = isValid;
};
return check(0,0,0);
}
};
DFS记忆化操作(就是剪枝)
于 2021-12-27 15:54:35 首次发布