-
Notifications
You must be signed in to change notification settings - Fork 0
/
word_break_hard.cpp
53 lines (45 loc) · 997 Bytes
/
word_break_hard.cpp
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <bits/stdc++.h>
using namespace std;
bool ispossible(string word, vector<string> &dict){
for(auto s: dict){
if(word == s) return true;
}
return false;
}
void solve(string s, string res, vector<string> &dict, int n, vector<string> &ans){
if(s.empty()){
ans.push_back(res);
return;
}
for(int i = 1; i <= s.length(); i++){
string word = s.substr(0, i);
if(ispossible(word, dict)){
solve(s.substr(i), res+word+" ", dict, n, ans);
}
}
}
vector<string> wordBreak(int n, vector<string> &dict, string s){
vector<string> ans;
solve(s, "", dict, n, ans);
return ans;
}
int main(){
int n;
cin >> n;
vector<string> dict;
string s;
for(int i = 0; i < n; i++){
cin >> s;
dict.push_back(s);
}
cin >> s;
vector<string> ans = wordBreak(n, dict, s);
if(ans.size() == 0){
cout << "EMPTY\n";
return 0;
}
for(int i = 0; i < ans.size(); i++){
cout << ans[i] << "\n";
}
return 0;
}