Skip to content

Commit b686671

Browse files
committed
Create 140. Word Break II.cpp
1 parent d9d9e9d commit b686671

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

140. Word Break II.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public:
3+
void dfs(int start, string &sentence, vector<string> &res, const string &s, const unordered_set<string> &dict, const vector<bool> &breakable){
4+
if(start == s.length()) res.push_back(sentence.substr(0, sentence.size() - 1));
5+
string substr, origin = sentence;
6+
for(int i = start; i < s.length(); ++i){
7+
substr = s.substr(start, i - start + 1);
8+
if(dict.find(substr) != dict.end() && breakable[i + 1]){
9+
sentence.append(substr).append(" ");
10+
dfs(i + 1, sentence, res, s, dict, breakable);
11+
sentence = origin;
12+
}
13+
}
14+
}
15+
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
16+
const size_t n = s.length();
17+
vector<string> res;
18+
string sentence = "", substr;
19+
vector<bool> breakable(n + 1, false);
20+
breakable[n] = true;
21+
for(int i = n - 1; i >= 0; --i){
22+
for(int j = i; j < n; ++j){
23+
substr = s.substr(i, j - i + 1);
24+
if(breakable[j + 1] && wordDict.find(substr) != wordDict.end())
25+
breakable[i] = true;
26+
}
27+
}
28+
dfs(0, sentence, res, s, wordDict, breakable);
29+
return res;
30+
}
31+
};

0 commit comments

Comments
 (0)