-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWord_Break_II.cpp
More file actions
32 lines (28 loc) · 897 Bytes
/
Word_Break_II.cpp
File metadata and controls
32 lines (28 loc) · 897 Bytes
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
vector<string> rec(const string& sentence, const vector<string>& dict,
unordered_map<string, vector<string>>& found) {
if(found.count(sentence)) {
return found[sentence];
}
int n = sentence.size();
vector<string> result;
for(int i = 1; i <= n; i++) {
string word = sentence.substr(0, i);
string rem = sentence.substr(i);
if(find(dict.begin(), dict.end(), word) != dict.end()) {
if(rem.empty()) {
result.push_back(word);
}
else {
for(auto& s: rec(rem, dict, found)) {
result.push_back(word + " " + s);
}
}
}
}
found[sentence] = result;
return result;
}
vector<string> Solution::wordBreak(string A, vector<string> &B) {
unordered_map<string, vector<string>> found;
return rec(A, B, found);
}