Given a stringSAnd a dictionary of wordsDict, Add spaces inSTo 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"]
.
There is no AC for this question, but a recursive version is made. The case of A and B after the last string of A times out and cannot be passed.
Sand -- [Dog]-> "cat sand dog"
/
Cat -- [sanddog]
/
[Catsanddog]
\
Cats -- [anddog]
\
And -- [Dog]-> "cats and dog"
From this structure, we can see that this problem can be broken down into the current problem + smaller-scale subproblems of the same type and solved recursively.
I used a vector <stirng> to record the results of each stage (PATH). When the string is searched (left> = right), it means that the result in the array is a result.
void wb(string s, int left, int right, unordered_set<string> &dict, vector<string> t, vector<string> &re) { if (s.length() <= 0) return; if (left >= right) { string k; for (int i=0; i<t.size(); i++) { if (i != t.size()-1) { k = k + t[i] + " "; } else k+=t[i]; } re.push_back(k); return; } //find matches for (const auto& elem: dict) { int len = (int)((string)elem).size(); if (left+len > s.length()) continue; string sub = s.substr(left, len); if (elem.compare(sub) == 0) { t.push_back(sub); wb(s, left+len, right, dict, t, re); if (t.size()) t.pop_back(); } }}vector<string> wordBreak(string s, unordered_set<string> &dict) { vector<string> ret; vector<string> t; wb(s, 0, s.size()-1, dict,t, ret); return ret;}
The two bugs encountered during the compilation process were caused by the lack of a good understanding of the program. The first bug was the T array. At first I passed the reference and found that the final result set doubled... The second is that after WB is called, t does not have pop, so that the content of the previous branch is taken to the next branch, causing disorder.
How to AC
[Leetcode] Word break II (TLE)