Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
Code:
<span style="font-size:14px;">class Solution {
public:
void DFS(vector<string> &results, const vector<vector<int> > &dp, int index, string result, const string &s) {
const int length = dp[index].size();
if (length == 0) return;
for (int i = 0; i < length; ++i) {
const int begin = dp[index][i];
if (begin == 0)
results.push_back(s.substr(0, index+1)+result);
else
DFS(results, dp, begin-1, " "+s.substr(begin, index-begin+1)+result, s);
}
}
vector<string> wordBreak(string s, unordered_set<string> &dict) {
vector<string> results;
const int length = s.size();
vector<vector<int> > dp(length, vector<int>());
for (int i = 0; i < length; ++i) {
if (dict.find(s.substr(0, i+1)) != dict.end())
dp[i].push_back(0);
for (int j = 0; j < i; ++j)
if (!dp[j].empty() && dict.find(s.substr(j+1, i-j)) != dict.end())
dp[i].push_back(j+1);
}
DFS(results, dp, length-1, "", s);
return results;
}
};</span>