-
Notifications
You must be signed in to change notification settings - Fork 0
/
0140_Word_Break_II.cpp
50 lines (42 loc) · 1.29 KB
/
0140_Word_Break_II.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#pragma GCC optimize("Ofast","inline","ffast-math","unroll-loops","no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native","f16c")
auto init = []()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 'c';
}();
class Solution {
public:
unordered_set<string> dict;
unordered_map<string, vector<string>> mp;
vector<string> solve(string &s) {
if(s.empty()) {
return {""};
}
if(mp.count(s))
return mp[s];
if(mp.count(s))
return mp[s];
vector<string> result;
for(int l = 1; l <= s.length(); l++) {
string currWord = s.substr(0, l);
if(dict.count(currWord)) {
string remainWord = s.substr(l);
vector<string> remainResult = solve(remainWord);
for(string &w : remainResult) {
string toAdd = currWord + (w.empty() ? "" : " ") + w;
result.push_back(toAdd);
}
}
}
return mp[s] = result;
}
vector<string> wordBreak(string s, vector<string>& wordDict) {
for(string &word : wordDict) {
dict.insert(word);
}
return solve(s);
}
};