[InterviewBit] Word Break II

Word Break II

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void helper(string& s, int p, string now, unordered_set<string>& us, vector<string>& res) {
if(p == s.length()) {
now.pop_back();
res.push_back(now);
} else {
string build = "";
for(int i = p; i < s.length(); i++) {
build.push_back(s[i]);
if(us.count(build)) helper(s,i+1,now + build + " ", us, res);
}
}
}
vector<string> Solution::wordBreak(string A, vector<string> &B) {
unordered_set<string> us(begin(B), end(B));
vector<string> res;
helper(A,0,"", us, res);
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/13/PS/interviewbit/word-break-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.