class Solution { public: vector wordBreak(string s, vector &wordDict) { unordered_map> m; return helper(s, wordDict, m); } vector helper(string s, vector &wordDict, unordered_map> &m) { if (m.count(s)) return m[s]; if (s.empty()) return {""}; vector ans; for (string word : wordDict) { if (word != s.substr(0, word.size())) continue; vector res = helper(s.substr(word.size()), wordDict, m); for (string str : res) { ans.push_back(word + (str.empty() ? "" : " ") + str); } } return m[s] = ans; } };