Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
Difficulty: Hard
public class Solution {
List<String> res = new ArrayList<String>();
public void helper(String ans, int index, List<String>[] listArray){
if(index == 0) {
res.add(ans.trim());
return;
}
if(listArray[index] == null){
return;
}
for(String word : listArray[index]){
helper(" " + word + ans, index - word.length(), listArray);
}
return;
}
public List<String> wordBreak(String s, Set<String> wordDict) {
ArrayList<String>[] listArray = new ArrayList[s.length() + 1];
listArray[0] = new ArrayList<String>();
for(int i = 0; i < s.length(); i++){
if(listArray[i] != null){
for(int j = i + 1; j <= s.length(); j++){
String sub = s.substring(i, j);
if(wordDict.contains(sub)){
if(listArray[j] == null){
listArray[j] = new ArrayList<String>();
}
listArray[j].add(sub);
}
}
}
}
helper("", s.length(), listArray);
return res;
}
}