- 回溯算法查询匹配单词
class Solution {
public:
unordered_map<string, int> word_map;
void mapping(vector<string>& wordDict)
{
for(auto &a : wordDict)
word_map[a]++;
}
vector<string> ret;
void dfs(string s, vector<string> tmp, int start)
{
if(start == s.size())
{
string str_tmp;
for(auto &a : tmp)
str_tmp += a + " ";
ret.push_back(str_tmp.substr(0, str_tmp.size() - 1));
return;
}
for(int i = start; i < s.size(); ++i)
{
string cur = s.substr(start, i - start + 1);
cout << cur << endl;
if(word_map.find(cur) != word_map.end())
{
cout << cur << endl;
tmp.push_back(cur);
dfs(s, tmp, i + 1);
tmp.pop_back();
}
}
}
vector<string> wordBreak(string s, vector<string>& wordDict) {
mapping(wordDict);
dfs(s, vector<string>(), 0);
return ret;
}
};