[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"]
.
Solution:
递归过程注意用空间换时间,以免TLE。
class Solution { public: vector<string>* res; int* visited; string srcStr; vector<string> word_break(int start, string s, unordered_set<string> &dict) { if(visited[start] == 1) return res[start]; vector<string> ans; int len = s.length(); if(len == 0) { visited[start] = 1; res[start] = ans; return ans; } //enumerate the first space location for(int i = 1;i <= len;i++) { //i is the number of char in the first string string firstStr = s.substr(0, i); string secondStr = s.substr(i, len - i); if(dict.find(firstStr) != dict.end()) { //first string can be found, get the break result of the second string vector<string> secondRes = word_break(start + i, secondStr, dict); if(i == len) { ans.push_back(firstStr); } else { if(secondRes.size() != 0) { for(int j = 0;j < secondRes.size();j++) { string cur = firstStr + " " + secondRes[j]; // cout << "cur = " << cur << endl; ans.push_back(cur); } } } } } res[start] = ans; visited[start] = 1; return ans; } vector<string> wordBreak(string s, unordered_set<string> &dict) { srcStr = s; vector<string> ans; if(s.length() == 0) return ans; res = new vector<string>[s.length() + 1]; visited = new int[s.length() + 1]; memset(visited, 0, (s.length() + 1) * sizeof(int)); ans = word_break(0, s, dict); return ans; } };