Skip to content

Commit 36a5a37

Browse files
committed
word_break_II
1 parent 6798e0e commit 36a5a37

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
123123
#### [137. single number II](https://github.com/hitzzc/go-leetcode/tree/master/single_number_II)
124124
#### [138. copy_list_with_random_pointer](https://github.com/hitzzc/go-leetcode/tree/master/copy_list_with_random_pointer)
125125
#### [139. word break](https://github.com/hitzzc/go-leetcode/tree/master/word_break)
126+
#### [140. word break II](https://github.com/hitzzc/go-leetcode/tree/master/word_break II)
126127

127128

128129

word_break_II/word_break_II.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include <string>
2+
#include <unordered_set>
3+
#include <vector>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
9+
vector<bool> history(s.size()+1, true);
10+
vector<string> results;
11+
vector<string> path;
12+
DFS(s, 0, results, path, history, wordDict);
13+
return results;
14+
}
15+
16+
void DFS(string s, int start, vector<string>& results, vector<string>& path, vector<bool>& history, unordered_set<string>& wordDict){
17+
if (start==s.size()){
18+
if (path.empty()) return;
19+
string ret = path[0];
20+
for (int i = 1; i < path.size(); ++i)
21+
ret = ret + " " + path[i];
22+
results.push_back(ret);
23+
return;
24+
}
25+
int pre_num = results.size();
26+
for (int end = start+1; end <= s.size(); ++end){
27+
if (!history[end] || wordDict.find(s.substr(start, end-start))==wordDict.end()) continue;
28+
path.push_back(s.substr(start, end-start));
29+
DFS(s, end, results, path, history, wordDict);
30+
path.pop_back();
31+
}
32+
if (results.size()==pre_num) history[start] = false;
33+
return;
34+
}
35+
};

0 commit comments

Comments
 (0)