Skip to content

Commit

Permalink
Time: 5 ms (6.50%), Space: 9.7 MB (22.44%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
Soumya-Kushwaha committed May 25, 2024
1 parent 039afe9 commit 25fdd6b
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions 0140-word-break-ii/0140-word-break-ii.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
//insert all the words in the set
unordered_set<string> set;
vector<string> res;
for(auto word:wordDict)
set.insert(word);
//to store the current string
string curr="";
findHelper(0,s,curr,set,res);
return res;
}

void findHelper(int ind,string s,string curr,unordered_set<string> set,vector<string>& res)
{
if(ind==s.length())
{
//we have reached end
curr.pop_back(); //remove the trailing space
res.push_back(curr);
}
string str="";
for(int i=ind;i<s.length();i++)
{
//get every substring and check if it exists in set
str.push_back(s[i]);
if(set.count(str))
{
//we have got a word in dict
//explore more and get other substrings
findHelper(i+1,s,curr+str+" ",set,res);
}
}
}
};

0 comments on commit 25fdd6b

Please sign in to comment.