# Hard-题目45：140. Word Break II

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 static List<String> wordBreak(String s, Set<String> dict) {
List<String> dp[] = new ArrayList[s.length()+1];
dp[0] = new ArrayList<String>();
for(int i=0; i<s.length(); i++){
//i是开始位置
if( dp[i] == null ) continue; //前面的部分必须是可以匹配的
for(String word:dict){
int len = word.length();
int end = i+len;
if(end > s.length()) continue;
if(s.substring(i,end).equals(word)){
if(dp[end] == null){
dp[end] = new ArrayList<String>();
}
}
}
}

if(dp[s.length()] == null) return ans;
ArrayList<String> tmp = new ArrayList<String>();
dfs(dp,s.length(),ans, tmp);
return ans;
}

public static void dfs(List<String> dp[],int end,List<String> res, ArrayList<String> tmp){
if(end <= 0){
String ans = tmp.get(tmp.size()-1);
for(int i=tmp.size()-2; i>=0; i--)
ans += (" " + tmp.get(i) );
return;
}
for(String str:dp[end]){
dfs(dp,end-str.length(), res, tmp);
tmp.remove(tmp.size()-1);
}
}
}

28ms,7.71%,16ms,12.53%
Cmershen的碎碎念：
NLP中的分词多是基于前向最大匹配算法、后向最大匹配算法等，比本题的暴力解法增加了概率模型。

#### LeetCode 140. Word Break II（单词切分）

2016-05-27 00:22:25

#### [Leetcode] 140. Word Break II 解题报告

2017-05-05 16:17:37

#### LeetCode 140. Word Break II (DP+DFS)

2015-02-23 10:39:42

#### leetcode 140:Word Break II 采用很巧妙的动态规划和DFS联合使用 JAVA源代码实现

2015-12-22 19:20:21

#### [Leetcode][python]Word Break/Word Break II/单词拆分/单词拆分 II

2017-12-07 08:20:07

#### LeetCode(140) Word Break II

2015-04-10 08:12:30

#### [leetcode-140]word breakII(java)

2015-08-18 17:44:38

#### [leetcode] 140. Word Break II 解题报告

2015-11-04 12:01:41

#### Algorithms—140.Word Break II

2015-10-20 15:57:10

#### Word Break II -- LeetCode

2014-03-29 00:48:08