还是DFS啊,我是dp弱逼。。就是不懂DP,快哭了都
DFS+备忘录。。避免重复状态的计算
PS.
map,unordered_map还是有区别的
map要严格的弱序
unordered_map要求能hash
typedef string::const_iterator Iter; map<pair<Iter,Iter> , bool> record; class Solution { public: bool isInterleave(string s1, string s2, string s3) { if(s1.size() + s2.size() != s3.size()) return false; record.clear(); return dfs(s1.begin() , s1.end() , s2.begin() , s2.end() , s3.begin(), s3.end()); } private: bool dfs(Iter b1 , Iter e1 , Iter b2 , Iter e2 , Iter b3 , Iter e3) { if(b3 == e3) { return true; } auto tmp = record.find(make_pair(b1,b2)); if(tmp != record.end()) return tmp->second; bool result = false; if(*b1 == *b3) result = dfs(b1+1,e1,b2,e2,b3+1,e3); if(result) { record.insert(make_pair(make_pair(b1,b2) , true)); return true; } if(*b2 == *b3) result = dfs(b1,e1,b2+1,e2,b3+1,e3); if(result) { record.insert(make_pair(make_pair(b1,b2) , true)); return true; } record.insert(make_pair(make_pair(b1,b2) , false)); return false; } };
by 1957