class Solution {
public List wordBreak(String s, List wordDict) {
List res = new ArrayList<>();
int max = 0, min = Integer.MAX_VALUE;
Set set = new HashSet<>();
for (String word : wordDict) {
set.add(word);
max = Integer.max(max, word.length());
min = Integer.min(min, word.length());
}
boolean f[] = new boolean[s.length() + 1];
f[0] = true;
for (int i = 1; i < s.length() + 1; i++) {
for (int j = Math.max(i - max, 0); j <= i - min; j++) {
if (f[j] && set.contains(s.substring(j, i))) {
f[i] = true;
break;
}
}
}
if (f[s.length()]) {
dfs(s, res, new StringBuilder(), set, 0, max, min);
}
return res;
}
private void dfs(String s, List res, StringBuilder sb, Set set, int index, int max, int min) {
if (index == s.length()) {
sb.deleteCharAt(sb.length() - 1);
res.add(sb.toString());
return;
}
String str;
int size;
for (int i = index + min; i <= s.length() && i <= index + max; i++) {
if (set.contains(str = s.substring(index, i))) {
size = sb.length();
sb.append(str).append(' ');
dfs(s, res, sb, set, i, max, min);
sb.delete(size, sb.length());
}
}
}
}