-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordBreakII.cpp
More file actions
26 lines (24 loc) · 865 Bytes
/
wordBreakII.cpp
File metadata and controls
26 lines (24 loc) · 865 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
// Source: https://leetcode.com/problems/word-break-ii/
// Author: Miao Zhang
// Date: 2021-01-21
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
map<string, vector<string>> dicts;
return wordBreak(s, wordDict, dicts);
}
vector<string> wordBreak(string s, vector<string>& wordDict, map<string, vector<string>> dicts) {
if (dicts.count(s)) return dicts[s];
if (s.empty()) return {""};
vector<string> res;
for (auto word: wordDict) {
if (s.substr(0, word.size()) != word) continue;
vector<string> tmp = wordBreak(s.substr(word.size()), wordDict, dicts);
for (auto str: tmp) {
res.push_back(word + (str.empty() ? "" : " " + str));
}
}
dicts[s] = res;
return res;
}
};