LeetCode 140. Word Break II
Solution1:我的答案
纯DFS,在第31个case时超时,还是记录一下。。
class Solution { // DFS
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> dict(wordDict.begin(), wordDict.end());
vector<string> res;
string temp = "";
int start = 0;
my_word(s, dict, res, temp, start);
return res;
}
private:
void my_word(string& s, unordered_set<string>& dict,
vector<string>& res, string& temp, int start) {
if (start == s.size()) {
res.push_back(temp);
return;
} else {
for (int i = start; i < s.size(); i++) {
string temp_str = s.substr(start, i - start + 1);
if (dict.count(temp_str)) {
if (!temp.size())
temp = temp_str;
else
temp += " " + temp_str;
my_word(s, dict, res, temp, i + 1);
if (temp.find(" ") != string::npos)
temp = temp.substr(0, temp.size() - temp_str.size() - 1);
else
temp = "";
}
}
}
return;
}
};
Solution2:
参考花花酱:https://zxi.mytechroad.com/blog/leetcode/leetcode-140-word-break-ii/
记忆化递归真牛逼啊!!!
Time complexity:
O(2n)
O
(
2
n
)
Space complexity:
O(2n)
O
(
2
n
)
// Author: Huahua
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> dict(wordDict.cbegin(), wordDict.cend());
return wordBreak(s, dict);
}
private:
// >> append({"cats and", "cat sand"}, "dog");
// {"cats and dog", "cat sand dog"}
vector<string> append(const vector<string>& prefixes, const string& word) {
vector<string> results;
for(const auto& prefix : prefixes)
results.push_back(prefix + " " + word);
return results;
}
const vector<string>& wordBreak(string s, unordered_set<string>& dict) {
// Already in memory, return directly
if(mem_.count(s)) return mem_[s];
// Answer for s
vector<string> ans;
// s in dict, add it to the answer array
if(dict.count(s))
ans.push_back(s);
for(int j=1;j<s.length();++j) {
// Check whether right part is a word
const string& right = s.substr(j);
if (!dict.count(right)) continue;
// Get the ans for left part
const string& left = s.substr(0, j);
const vector<string> left_ans =
append(wordBreak(left, dict), right);
// Notice, can not use mem_ here,
// since we haven't got the ans for s yet.
ans.insert(ans.end(), left_ans.begin(), left_ans.end());
}
// memorize and return
mem_[s].swap(ans);
return mem_[s];
}
private:
unordered_map<string, vector<string>> mem_;
};