-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWord_Break_II.cpp
More file actions
26 lines (26 loc) · 881 Bytes
/
Copy pathWord_Break_II.cpp
File metadata and controls
26 lines (26 loc) · 881 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
class Solution {
public:
unordered_map<string,vector<string>> ump;
vector<string> recursive(string s, unordered_set<string>& ust){
if(ump.count(s))
return ump[s];
vector<string> res;
if(ust.count(s))
res.push_back(s);
for(int i=s.size()-1; i>0; i--){
string last_word = s.substr(i);
if(ust.count(last_word)){
vector<string> prefix = recursive(s.substr(0,i),ust);
for(int i=0; i<prefix.size(); i++)
prefix[i] += " "+last_word;
res.insert(res.end(),prefix.begin(),prefix.end());
}
}
ump[s] = res;
return res;
}
vector<string> wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> ust(wordDict.begin(),wordDict.end());
return recursive(s,ust);
}
};