This is an enhanced version of the previous question, where all possible segmentation words need to be returned. For example:
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
Use DP to get each start-to-end to meet the conditions in Word break 1, and then use DFS to recursively solve the answer. Note that, for the convenience of recursion, pay attention to the DP to one more dp[s.size () + 1] Length
classSolution { Public: // $ voiddfs140 (stringS, unordered_set<string> &dict, vector<string> &ans, vector<string> &vec,BOOLDp[],intstart) { if(Start = =s.size ()) { if(Vec.size () >0) { stringstr = vec[0]; for(inti =1; I < vec.size (); i++) {str= str +" "+Vec[i]; } ans.push_back (str); } return ; } for(inti =1; I <= s.size ()-Start; i++) { if(Dict.count (S.substr (Start, i)) && Dp[start +i]) {Vec.push_back (S.substr (Start, i)); dfs140 (S, dict, ans, VEC, DP, start+i); Vec.pop_back (); }}} vector<string> Wordbreak (stringS, unordered_set<string> &dict) { BOOLDp[s.size () +1];//different from the previous question, here need one more, the last one is true, in order to recursion time convenientMemset (DP,0,sizeof(DP)); for(inti =0; I < s.size (); i++) { if(Dict.count (S.substr (i, s.size ()-i))) Dp[i]=1; } for(inti = s.size ()-1; I < s.size (); i--) { if(Dp[i] = =false) { for(intj = i; J < S.size (); J + +) { if(Dict.count (S.substr (i, J-i +1)) && Dp[j +1]) Dp[i]=true; if(Dp[i]) Break; }}} dp[s.size ()]=1; Vector<string>ans, tmp; dfs140 (S, dict, ANS, TMP, DP,0); returnans; }};
The idea is much like Leetcode palindrome partitioning II
LEETCODE[140] Word Break II