Skip to content

Commit cb15c2a

Browse files
committed
Runtime 0 ms (Top 100.0%) | Memory 7.0 MB (Top 5.89%)
1 parent bbb07bf commit cb15c2a

File tree

1 file changed

+21
-22
lines changed

1 file changed

+21
-22
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,31 @@
1-
// Runtime: 4 ms (Top 33.21%) | Memory: 7.3 MB (Top 37.14%)
2-
31
class Solution {
42
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);
116
return;
127
}
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);
2417
}
18+
helper(s,dict,start,index+1,current,ans);
19+
return;
2520
}
2621
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);
3028
return ans;
29+
3130
}
3231
};

0 commit comments

Comments
 (0)