2014.2.27 02:03
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"]
.
Solution:
This problem request you to find out all breaking methods.
I tried DFS, but first I got an TLE because I looked up the segment in the dictionary in the recursive function. Later I realized it would be better to look up every segment in the dictionary and store the result in a 2d array.
After this optimization things should be good enough, but the result was still TLE.
Then I changed the direction of DFS, from right to left and got an AC at last. Don't know why, maybe the input data will tell me. Forget about it, pal.
Total time complexity is O(n!). Space complexity is O(n^2).
Accepted code:
1 // 3CE, 2TLE, 1WA, 1AC, DFS from right to left will do, while from left to right it wouldn't. 2 class Solution { 3 public: 4 vector<string> wordBreak(string s, unordered_set<string> &dict) { 5 result.clear(); 6 n = (int)s.length(); 7 if (n == 0 || dict.empty()) { 8 return result; 9 } 10 11 dp.resize(n); 12 int i, j; 13 for (i = 0; i < n; ++i) { 14 dp[i].resize(n - i); 15 } 16 17 string str; 18 for (i = 0; i < n; ++i) { 19 for (j = i; j < n; ++j) { 20 str = s.substr(i, j - i + 1); 21 if (dict.find(str) != dict.end()) { 22 dp[i][j - i] = 1; 23 } else { 24 dp[i][j - i] = 0; 25 } 26 } 27 } 28 29 words.clear(); 30 dfs(s, n - 1); 31 for (i = 0; i < n; ++i) { 32 dp[i].clear(); 33 } 34 dp.clear(); 35 36 return result; 37 } 38 private: 39 int n; 40 vector<string> result; 41 vector<string> words; 42 vector<vector<int> > dp; 43 44 void dfs(const string &s, int idx) { 45 if (idx == -1) { 46 getResultString(); 47 } else { 48 int i; 49 for (i = 0; i <= idx; ++i) { 50 if (dp[i][idx - i]) { 51 words.push_back(s.substr(i, idx - i + 1)); 52 dfs(s, i - 1); 53 words.pop_back(); 54 } 55 } 56 } 57 } 58 59 void getResultString() { 60 if (words.empty()) { 61 return; 62 } 63 string str = words[(int)words.size() - 1]; 64 int i; 65 for (i = (int)words.size() - 2; i >= 0; --i) { 66 str += (" " + words[i]); 67 } 68 result.push_back(str); 69 } 70 };