给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。
说明:
示例 1:
输入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
输出:
[
"cats and dog",
"cat sand dog"
]
示例 2:
输入:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
输出:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
解释: 注意你可以重复使用字典中的单词。
示例 3:
输入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
输出:
[]
核心就是 DP + DFS
利用 单词划分 的 DP 方法判断是否能够成功划分,能划分则利用 DFS 确定划分情况。
参考网上的思路,若不剪枝,直接 DFS 会 TLE
class Solution {
//DP + DFS
public List wordBreak(String s, List wordDict) {
List res = new ArrayList();
//dp 判断能否拆分
boolean[] dp = new boolean[s.length()+1];
dp[0] = true;
for(int i=0 ;i<=s.length();i++){
for(int j=0;jif(dp[j] && wordDict.contains(s.substring(j,i))){
dp[i]=true;
break;
}
}
}
if(!dp[s.length()]){
return res;
}
StringBuilder sb = new StringBuilder();
dfs(s,wordDict,sb,res,0);
return res;
}
private void dfs(String s,List wordDict,StringBuilder sb,List res,int start){
if(start == s.length()){
res.add(sb.toString().trim());
return;
}
for(int i=start+1;i<=s.length();i++){
String str = s.substring(start,i);
if(wordDict.contains(str)){
int length = sb.length();
sb.append(str).append(" ");
dfs(s,wordDict,sb,res,i);
sb.setLength(length);
}
}
}
}