LeetCode-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"]
.
动归
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: void sub(vector<vector<int> >& str,string& s,int index,string& one, vector<string>& ret){ if(index==0){ ret.push_back(one); } else{ int length=one.length(); for(int i=0;i<str[index].size();i++){ if(index==s.length()){ one=s.substr(str[index][i],index-str[index][i])+one; } else{ one=s.substr(str[index][i],index-str[index][i])+" "+one; } sub(str,s,str[index][i],one,ret); one=one.substr(one.length()-length,length); } } } vector<string> wordBreak(string s, unordered_set<string> &dict) { int maxLen=0; for(unordered_set<string>::iterator it=dict.begin();it!=dict.end();it++){ if( (*it).length()>maxLen)maxLen=(*it).length(); } string tmp; vector<vector<int> >str; vector<bool>acc; acc.resize(s.length()+1,false); str.resize(s.length()+1); acc[0]=true; int i=0; if(acc[i]){ int top=min(maxLen,(int)s.length()-i); for(int j=1;j<=top;j++){ tmp=s.substr(i,j); if(dict.find(tmp)!=dict.end()){ acc[i+j]=true; str[i+j].push_back(0); } } } for(int i=1;i<s.length();i++){ if(acc[i]){ int top=min(maxLen,(int)s.length()-i); for(int j=1;j<=top;j++){ tmp=s.substr(i,j); if(dict.find(tmp)!=dict.end()){ acc[i+j]=true; str[i+j].push_back(i); } } } } string one=""; vector<string> ret; sub(str,s,s.length(),one,ret); return ret; } };