回溯算法查询匹配单词 class Solution { public:unordered_map<string, int> word_map;void mapping(vector<string>& wordDict){for(auto &a : wordDict)word_map[a]++;}vector<string> ret;// s: 原始字符串// tmp: 已查询到的单词// start: 此次查询起点的字符串中下标void dfs(string s, vector<string> tmp, int start){// 匹配完成,tmp中单词以此插入结果数组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);// 回溯,继续找当前start开始更长的单词是否在wordDict中出现tmp.pop_back();}}}vector<string> wordBreak(string s, vector<string>& wordDict) {mapping(wordDict);dfs(s, vector<string>(), 0);return ret;} };