Word Break II

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

Word Break II

Solution1

Recursive

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
public ArrayList<String> wordBreak(String s, List<String> dict) {
Map<String, ArrayList<String>> memo = new HashMap<>();
return wordBreakHelper(s, dict, memo);
}

public ArrayList<String> wordBreakHelper(String s, List<String> dict, Map<String, ArrayList<String>> memo) {
if (memo.containsKey(s)) {
return memo.get(s);
}

ArrayList<String> result = new ArrayList<>();
if (s.length() == 0) {
return result;
}

if (dict.contains(s)) {
result.add(s);
}

for (int length = 1; length < s.length(); length++) {
String word = s.substring(0, length);
if (!dict.contains(word)) {
continue;
}

String suffix = s.substring(length);
List<String> segmentations = wordBreakHelper(suffix, dict, memo);
for (String segmentation : segmentations) {
result.add(word + " " + segmentation);
}
}
memo.put(s, result);
return result;
}