-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWord_Break_Part_2.cpp
50 lines (45 loc) · 1.11 KB
/
Word_Break_Part_2.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
// https://practice.geeksforgeeks.org/problems/word-break-part-23249/1
class Solution{
public:
vector <string> res;
bool search(string s, vector<string> &dict, int n)
{
for(int i = 0; i<n; i++)
{
if(dict[i]==s)
return true;
}
return false;
}
void solve(int n,vector<string> &dict,int i,int j,string sent,string s)
{
string copy = sent;
if(s.length()-1==j)
{
string temp = s.substr(i,j-i+1);
if(search(temp,dict,n))
{
sent = sent + temp;
res.push_back(sent);
}
return;
}
string temp = s.substr(i,j-i+1);
if(search(temp,dict,n))
{
sent = sent + temp + " ";
solve(n,dict,j+1,j+1,sent,s);
sent = copy;
solve(n,dict,i,j+1,sent,s);
}
else
{
solve(n,dict,i,j+1,sent,s);
}
}
vector<string> wordBreak(int n, vector<string>& dict, string s)
{
solve(n,dict,0,0,"",s);
return res;
}
};