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"]
.
枚举的题,一般用DFS+Backtracking做,此题会超时,那么要辅助memoization, 保存之前得到的结果.
怎么mem?
1,借鉴word break I, 保存能否该index之后能否break: boolean[s.length() + 1]
2, 保存详细的分法结果: HashMap<Integer,List<String>>
public class Solution {
List<String> res = new ArrayList<String>();
public List<String> wordBreak(String s, Set<String> dict) {
if (s == null || s.length() == 0) return res;
boolean[] canBreak = new boolean[s.length()+1];
for (int i = 0; i <= s.length(); i++) {
canBreak[i] = true;
}
helper(s, dict, "", 0, canBreak);
return res;
}
public void helper(String s, Set<String> dict, String cur, int beg, boolean[] canbreak) {
if (beg == s. length()){
res.add(cur);
return;
}
boolean flag = false;
for (int i = beg + 1; i <= s.length(); i++) {
if (!canbreak[i]) {
continue;
}
String temp = s.substring(beg, i);
if(!dict.contains(temp)){
continue;
}
flag = true;
String pre = new String(cur);
if (cur.isEmpty()) {
cur = temp;
}else{
cur = cur + " " + temp;
}
helper(s, dict, cur, i, canbreak);
cur = pre;
}
canbreak[beg] = flag; //初始为true,如果从beg+1...end都不能再分了,设为false
}
}
public class Solution {
HashMap<Integer, List<String>> map = new HashMap<>();
public List<String> wordBreak(String s, Set<String> dict) {
if (s == null || s.length() == 0) return null;
return helper(s, dict, 0);
}
public List<String> helper(String s, Set<String> dict, int beg) {
List<String> res = new ArrayList<String>();
if (beg >= s.length()) return res;
if (map.containsKey(beg)) {
return map.get(beg);
}
for (int i = beg + 1; i <= s.length(); i++) {
String sub = s.substring(beg, i);
if (!dict.contains(sub)) {
continue;
}
if (i == s.length()) {
res.add(sub);
}else{
List<String> later = helper(s, dict, i);
for(String temp : later){
temp = sub + " " + temp;
res.add(temp);
}
}
}
map.put(beg, res);
return res;
}
}