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"]
.
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
int len = s.size();
vector<vector<bool>> flag(len, vector<bool>(len, false));
for(int i = 0; i < len; i++)
{
for(int j = 0; j < len; j++)
{
if(dict.find(s.substr(i,j-i+1)) != dict.end())
flag[i][j] = true;
}
}
vector<string> result;
for(int i = len-1; i >= 0; i--)
{
if(flag[i][len-1])
{
string str = s.substr(i, len-i);
back(flag, i-1, s, str, result);
}
}
return result;
}
void back(vector<vector<bool>> &flag, const int &i, const string &s, string str, vector<string> &result)
{
if(i==-1)
{
result.push_back(str);
return;
}
for(int j = 0; j <= i; j++)
{
if(flag[j][i])
{
string cur_str = s.substr(j, i-j+1) + " " + str;
back(flag, j-1, s, cur_str, result);
}
}
}
};