![](https://img2020.cnblogs.com/blog/1505779/202003/1505779-20200319164940999-1322623419.png)
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
if (m.count(s)) return m[s]; //判断map中有没有s
if (s.empty()) return {""};
vector<string> res;
for (string word : wordDict) {
if (s.substr(0, word.size()) != word) continue; //进行前缀判断
for (string r : wordBreak(s.substr(word.size()), wordDict)) {
//DFS搜索 返回值为当前前缀对应的解 被分割好了
//sustr去除前缀
res.push_back(word + (r.empty() ? "" : " ") + r);
//整合答案
}
}
return m[s] = res;
}
private:
unordered_map<string, vector<string>> m;
};
作者:LightAc
出处:https://www.cnblogs.com/lightac/
联系:
Email: dzz@stu.ouc.edu.cn
QQ: 1171613053
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。