思路:
这题做出来以后成就感爆棚啊…第一个是我写的一个标准DFS, 但过不去大样本, 会超时. 第二个版本是借助Word Break http://blog.csdn.net/hiimdaosui/article/details/52457700 里面的DP数组做剪枝, 这样就可以过大样本了.
void dfs(vector<string>& res, string& candidate, string& s, unordered_set<string>& wordDict, int start) {
if (start == s.length()) {
candidate.pop_back();
res.push_back(candidate);
return;
}
for (int i = start; i < s.length(); i++) {
string temp = candidate;
string cur = s.substr(start, i - start + 1);
if (wordDict.count(cur)) {
candidate += cur + " ";
dfs(res, candidate, s, wordDict, i + 1);
candidate = temp;
}
}
}
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
vector<string> res;
string candidate = "";
dfs(res, candidate, s, wordDict, 0);
return res;
}
void dfs(vector<string>& res, string& candidate, string& s, unordered_set<string>& wordDict, int start, bool breakable[]) {
if (start == s.length()) {
candidate.pop_back();
res.push_back(candidate);
return;
}
for (int i = start; i < s.length(); i++) {
string cur = s.substr(start, i - start + 1);
if (breakable[i + 1] && wordDict.count(cur)) {
string temp = candidate;
candidate += cur + " ";
dfs(res, candidate, s, wordDict, i + 1, breakable);
candidate = temp;
}
}
}
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
int slen = s.length();
vector<string> res;
if (! slen) return res;
bool breakable[slen + 1] = {0};
breakable[0] = true;
for (int i = 1; i <= slen; i++) {
for (int j = 0; j < i; j++) {
string cur = s.substr(j, i - j);
if (breakable[j] && wordDict.count(cur)) {
breakable[i] = true;
break;
}
}
}
string candidate = "";
if (breakable[slen])
dfs(res, candidate, s, wordDict, 0, breakable);
return res;
}