Skip to content

Commit 971705f

Browse files
authored
Create 140. Word Break II (#488)
2 parents a4fd735 + e3109f6 commit 971705f

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

140. Word Break II

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
private:
3+
void backtrack(string& s, int index, unordered_set<string>& set, string curr, vector<string>& res){
4+
if (index == s.length()) {res.push_back(curr); return;}
5+
string t = "";
6+
for (int i = index; i < s.size(); i++){
7+
t += s[i];
8+
if (set.find(t) != set.end()){
9+
backtrack(s, i+1, set, curr + t + (i < s.length()-1 ? " ":""), res);
10+
}
11+
}
12+
}
13+
public:
14+
vector<string> wordBreak(string s, vector<string>& wordDict) {
15+
vector<string> res;
16+
unordered_set<string> set(wordDict.begin(), wordDict.end());
17+
backtrack(s, 0, set, "", res);
18+
return res;
19+
}
20+
};

0 commit comments

Comments
 (0)