1
- // Runtime: 4 ms (Top 33.21%) | Memory: 7.3 MB (Top 37.14%)
2
-
3
1
class Solution {
4
2
public:
5
- vector<string> ans;
6
- void solve (string& a,unordered_set<string>& words,int idx,string cstr)
7
- {
8
- if (idx>=a.length ())
9
- {
10
- ans.push_back (cstr);
3
+ void helper (string s, unordered_set<string>& dict,int start, int index,string current,vector<string>& ans){
4
+ if (start==s.size ()){
5
+ ans.push_back (current);
11
6
return ;
12
7
}
13
- if (cstr.length ()!=0 )
14
- {
15
- cstr+=" " ;
16
- }
17
- for (int i=idx;i<a.length ();++i)
18
- {
19
- string str=a.substr (idx,i-idx+1 );
20
- if (words.find (str)!=words.end ())
21
- {
22
- solve (a,words,i+1 ,cstr+str);
23
- }
8
+ if (index ==s.size ()) return ;
9
+
10
+ string sub=s.substr (start,index -start+1 );
11
+
12
+ if (dict.count (sub)>0 ){
13
+ string recursion;
14
+ if (current.size ()==0 ) recursion=sub;
15
+ else recursion=current+" " +sub;
16
+ helper (s,dict,index +1 ,index +1 ,recursion,ans);
24
17
}
18
+ helper (s,dict,start,index +1 ,current,ans);
19
+ return ;
25
20
}
26
21
vector<string> wordBreak (string s, vector<string>& wordDict) {
27
- ans.clear ();
28
- unordered_set<string> st (wordDict.begin (),wordDict.end ());
29
- solve (s,st,0 ," " );
22
+ unordered_set<string> dict;
23
+ for (int i=0 ;i<wordDict.size ();i++){
24
+ dict.insert (wordDict[i]);
25
+ }
26
+ vector<string> ans;
27
+ helper (s,dict,0 ,0 ," " ,ans);
30
28
return ans;
29
+
31
30
}
32
31
};
0 commit comments