标签:
Well, it seems that many people meet the TLE problem. Well, I use a simple trick in my code to aoivd TLE. That is, each time before I try to break the string, I call the wordBreak()
function from Word Break first to see whether it is breakable. If it is not breakable, then we simply return an empty vector of string. Otherwise, we break it using backtracking.
The idea of backtracking is also typical. Start from 0
index of the string, each time we see a new word, add it to a temporary solution string sol
. When we pass the end of the string, push sol
to a result vector res
. Then we need to recover sol
back to its original status before the word was added. So I simply record another temporary variable temp
each time before I add a word to sol
.
The code is as follows. I hope it to be self-explanatory enough.
1 bool isWordBreak(string& s, unordered_set<string>& wordDict) { 2 vector<bool> dp(s.length() + 1, false); 3 dp[0] = true; 4 int minlen = INT_MAX; 5 int maxlen = INT_MIN; 6 for (string word : wordDict) { 7 minlen = min(minlen, (int)word.length()); 8 maxlen = max(maxlen, (int)word.length()); 9 } 10 for (int i = 1; i <= s.length(); i++) { 11 for (int j = i - minlen; j >= max(0, i - maxlen); j--) { 12 if (dp[j] && wordDict.find(s.substr(j, i - j)) != wordDict.end()) { 13 dp[i] = true; 14 break; 15 } 16 } 17 } 18 return dp[s.length()]; 19 } 20 void breakWords(string s, int idx, unordered_set<string>& wordDict, string& sol, vector<string>& res) { 21 if (idx == s.length()) { 22 sol.resize(sol.length() - 1); 23 res.push_back(sol); 24 return; 25 } 26 for (int i = idx; i < s.length(); i++) { 27 string word = s.substr(idx, i - idx + 1); 28 if (wordDict.find(word) != wordDict.end()) { 29 string tmp = sol; 30 sol += word + " "; 31 breakWords(s, i + 1, wordDict, sol, res); 32 sol = tmp; 33 } 34 } 35 } 36 vector<string> wordBreak(string s, unordered_set<string>& wordDict) { 37 string sol; 38 vector<string> res; 39 if (!isWordBreak(s, wordDict)) return res; 40 breakWords(s, 0, wordDict, sol, res); 41 return res; 42 }
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4565214.html