/*
* @lc app=leetcode id=140 lang=cpp
*
* [140] Word Break II
*/
// @lc code=start
class Solution {
unordered_map<string, vector<string>> m;
public:
vector<string> dfs(string s, unordered_set<string> &words) {
if (m.count(s)) return m[s];
vector<string> res;
for (int i = 0; i < s.length() - 1; ++i) {
const auto b = s.substr(i + 1);
if (!words.count(b)) continue;
auto l = dfs(s.substr(0, i + 1), words);
if (!l.empty()) {
for (const auto a : l) {
res.push_back(a + " " + b);
}
}
}
if (words.count(s)) res.push_back(s);
m[s] = res;
return res;
}
vector<string> wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> words(wordDict.begin(), wordDict.end());
return dfs(s, words);
}
};
// @lc code=end