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"]
.
public class Solution {
public List<String> wordBreak(String s, Set<String> dict) {
boolean[] f = new boolean[s.length()+1];
boolean[][] log= new boolean[s.length()+1][s.length()+1];
f[0]=true; log[0][0]=true;
for(int i=1; i<= s.length(); i++){
for(int j=i-1; j>=0; j--){
String sub = s.substring(j,i);
if(f[j] && dict.contains(sub)){
f[i]=true;
log[j][i]=true;
}
}
}
List<String> result = new ArrayList<>();
List<String> path = new ArrayList<>();
generatePath(s, log, path, result, s.length());
return result;
}
private void generatePath(String s, boolean[][] log, List<String> path, List<String> result, int index){
if(index == 0){
StringBuilder sb = new StringBuilder();
for(String sub : path)
sb.insert(0, sub+" ");
sb.deleteCharAt(sb.length()-1);
result.add(sb.toString());
return;
}
for(int i=0; i<s.length(); i++){
if(log[i][index]==true){
path.add(s.substring(i, index));
generatePath(s,log,path,result,i);
path.remove(path.size()-1);
}
}
}
}
hints: 1. return string[] <= each word in sentence is existed in dict (relative position is not changed) <= traverse string, make sure each segment in string is existed in dict <= how many ways are there for string to be put and all segments are in dict?
2. dp, traverse till the end, so that I can make sure the string can be fully cut. save the result once fully cut. 这个只能求出其中一个解。题目中要求多个解。这样不仅要记录所有的words(通过Log[][]),还要从后往前查找每一个可能组成的单词(dfs/递归),每次找到前面的一个单词之后。以这个单词为结尾继续往前搜索。一直到 index 是0.说明一次从后往前扫描完毕保存。
3. 函数/类的使用:StringBuilder.insert(); StringBuilder.deleteCharAt(),