这道题相似  Word Break 推断能否把字符串拆分为字典里的单词 @LeetCode 只不过要求计算的并不不过能否拆分,而是要求出全部的拆分方案。

因此用递归。

可是直接递归做会超时,原因是LeetCode里有几个非常长可是无法拆分的情况。所以就先跑一遍Word Break,先推断能否拆分。然后再进行拆分。

递归思路就是,逐一尝试字典里的每个单词,看看哪一个单词和S的开头部分匹配,假设匹配则递归处理S的除了开头部分,直到S为空。说明能够匹配。

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) {
List<String> list = new ArrayList<String>();
List<String> ret = new ArrayList<String>();
rec(s, dict, list, ret);
return ret;
} public void rec(String s, Set<String> dict, List<String> list, List<String> ret) {
if(!isBreak(s, dict)){ // test before run to avoid TLE
return;
}
if(s.length() == 0) {
String concat = "";
for(int i=0; i<list.size(); i++) {
concat += list.get(i);
if(i != list.size()-1) {
concat += " ";
}
}
ret.add(concat);
return;
} for(String cur : dict) {
if(cur.length() > s.length()) { // avoid out of boundary
continue;
}
String substr = s.substring(0, cur.length());
if(substr.equals(cur)) {
list.add(substr);
rec(s.substring(cur.length()), dict, list, ret);
list.remove(list.size()-1);
}
}
} public boolean isBreak(String s, Set<String> dict) {
boolean[] canBreak = new boolean[s.length()+1];
canBreak[0] = true; for(int i=1; i<=s.length(); i++) {
boolean flag = false;
for(int j=0; j<i; j++) {
if(canBreak[j] && dict.contains(s.substring(j,i))) {
flag = true;
break;
}
}
canBreak[i] = flag;
}
return canBreak[s.length()];
}
}
05-20 01:16
查看更多