Word Break II
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"]
.
解分为三步:
(1)构造两级向量(vector<vector<int> > v)
链式存放前一个字符的位置。
(2)基于向量v逆向递归寻找词,借助栈
[dog --> [dog, sand --> [dog, sand, cat
[dog, and --> [dog, and, cats
(3)出栈时词以空格隔开,存入ret向量
"cat sand dog"
"cats and dog"
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
vector<string> ret;
string news = "" + s;
int n = news.size();
vector<vector<int> > v(n);
vector<bool> bpos(n, false);
bpos[] = true;
for(int i = ; i < n; i ++)
{
for(int j = ; j < i; j ++)
{
if(bpos[j] == true && wordDict.find(news.substr(j+, i-j)) != wordDict.end())
{
bpos[i] = true;
v[i].push_back(j);
}
}
}
if(bpos[n-] == false)
return ret;
else
{
stack<string> stk;
genRet(ret, news, v, stk, n-);
return ret;
}
}
void genRet(vector<string>& ret, string news, vector<vector<int> > v, stack<string> stk, int bpos)
{
if(bpos == )
{// generate final string
string str;
while(!stk.empty())
{
string top = stk.top();
stk.pop();
str += (top + " ");
}
str.erase(str.end()-);
ret.push_back(str);
}
else
{
for(int i = ; i < v[bpos].size(); i ++)
{
string cur = news.substr(v[bpos][i]+, bpos-v[bpos][i]);
stk.push(cur);
genRet(ret, news, v, stk, v[bpos][i]);
stk.pop();
}
}
}
};