-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordBreakii.java
More file actions
36 lines (28 loc) · 1020 Bytes
/
wordBreakii.java
File metadata and controls
36 lines (28 loc) · 1020 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
Set<String> dict = new HashSet<>(wordDict);
Map<String, List<String>> memo = new HashMap<>();
return backtrack(s, dict, memo);
}
private List<String> backtrack(String s, Set<String> dict, Map<String, List<String>> memo) {
if (memo.containsKey(s)) {
return memo.get(s);
}
List<String> result = new ArrayList<>();
if (s.length() == 0) {
result.add("");
return result;
}
for (int i = 1; i <= s.length(); i++) {
String prefix = s.substring(0, i);
if (dict.contains(prefix)) {
List<String> suffixWays = backtrack(s.substring(i), dict, memo);
for (String way : suffixWays) {
result.add(prefix + (way.isEmpty() ? "" : " ") + way);
}
}
}
memo.put(s, result);
return result;
}
}