Skip to content

Commit 97ad4e5

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 140_Word_Break_II.java
1 parent 538af44 commit 97ad4e5

File tree

2 files changed

+34
-32
lines changed

2 files changed

+34
-32
lines changed

Backtracking/140_Word_Break_II.java

Lines changed: 0 additions & 32 deletions
This file was deleted.
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public List<String> wordBreak(String s, List<String> wordDict) {
3+
Set<String> dict = new HashSet<>(wordDict);
4+
Map<String, List<String>> memo = new HashMap<>();
5+
6+
return helper(s, dict, memo);
7+
}
8+
9+
private List<String> helper(String s, Set<String> dict, Map<String, List<String>> memo) {
10+
if (memo.containsKey(s)) {
11+
return memo.get(s);
12+
}
13+
14+
List<String> result = new ArrayList<>();
15+
if (dict.contains(s)) {
16+
result.add(s);
17+
}
18+
19+
for (int i = 1; i < s.length(); i++) {
20+
String word = s.substring(0, i);
21+
22+
if (dict.contains(word)) {
23+
List<String> tmp = helper(s.substring(i), dict, memo);
24+
25+
for (String remainder : tmp) {
26+
result.add(word + " " + remainder);
27+
}
28+
}
29+
}
30+
31+
memo.put(s, result);
32+
return result;
33+
}
34+
}

0 commit comments

Comments
 (0)