Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

Example 1:

Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
  "cats and dog",
  "cat sand dog"
]

Example 2:

Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
  "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.

Example 3:

Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
[]

139. Word Break 的拓展,那道题只是让判断是否可以拆分,而这道题要求输出所有可能的拆分组合。

解法:dp + dfs,先用dp计算是否可以拆分,然后用dfs求出具体拆分的组合。

Java:

public static List<String> wordBreak(String s, Set<String> dict) {
//create an array of ArrayList<String>
List<String> dp[] = new ArrayList[s.length()+1];
dp[0] = new ArrayList<String>(); for(int i=0; i<s.length(); 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>();
}
dp[end].add(word);
}
}
} List<String> result = new LinkedList<String>();
if(dp[s.length()] == null)
return result; ArrayList<String> temp = new ArrayList<String>();
dfs(dp, s.length(), result, temp); return result;
} public static void dfs(List<String> dp[],int end,List<String> result, ArrayList<String> tmp){
if(end <= 0){
String path = tmp.get(tmp.size()-1);
for(int i=tmp.size()-2; i>=0; i--){
path += " " + tmp.get(i) ;
} result.add(path);
return;
} for(String str : dp[end]){
tmp.add(str);
dfs(dp, end-str.length(), result, tmp);
tmp.remove(tmp.size()-1);
}
}

Java:

public List<String> wordBreak(String s, Set<String> wordDict) {
ArrayList<String> [] pos = new ArrayList[s.length()+1];
pos[0]=new ArrayList<String>(); for(int i=0; i<s.length(); i++){
if(pos[i]!=null){
for(int j=i+1; j<=s.length(); j++){
String sub = s.substring(i,j);
if(wordDict.contains(sub)){
if(pos[j]==null){
ArrayList<String> list = new ArrayList<String>();
list.add(sub);
pos[j]=list;
}else{
pos[j].add(sub);
} }
}
}
} if(pos[s.length()]==null){
return new ArrayList<String>();
}else{
ArrayList<String> result = new ArrayList<String>();
dfs(pos, result, "", s.length());
return result;
}
} public void dfs(ArrayList<String> [] pos, ArrayList<String> result, String curr, int i){
if(i==0){
result.add(curr.trim());
return;
} for(String s: pos[i]){
String combined = s + " "+ curr;
dfs(pos, result, combined, i-s.length());
}
} 

Java:

public class Solution {
Map<String, List<String>> done = new HashMap<>();
Set<String> dict; public List<String> wordBreak(String s, Set<String> dict) {
this.dict = dict;
done.put("", new ArrayList<>());
done.get("").add(""); return dfs(s);
} List<String> dfs(String s) {
if (done.containsKey(s)) {
return done.get(s);
}
List<String> ans = new ArrayList<>(); for (int len = 1; len <= s.length(); len++) {
String s1 = s.substring(0, len);
String s2 = s.substring(len); if (dict.contains(s1)) {
List<String> s2_res = dfs(s2);
for (String item : s2_res) {
if (item == "") {
ans.add(s1);
} else {
ans.add(s1 + " " + item);
}
}
}
}
done.put(s, ans);
return ans;
}
} 

Python:

class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: Set[str]
:rtype: List[str]
"""
n = len(s) max_len = 0
for string in wordDict:
max_len = max(max_len, len(string)) can_break = [False for _ in xrange(n + 1)]
valid = [[False] * n for _ in xrange(n)]
can_break[0] = True
for i in xrange(1, n + 1):
for l in xrange(1, min(i, max_len) + 1):
if can_break[i-l] and s[i-l:i] in wordDict:
valid[i-l][i-1] = True
can_break[i] = True result = []
if can_break[-1]:
self.wordBreakHelper(s, valid, 0, [], result)
return result def wordBreakHelper(self, s, valid, start, path, result):
if start == len(s):
result.append(" ".join(path))
return
for i in xrange(start, len(s)):
if valid[start][i]:
path += [s[start:i+1]]
self.wordBreakHelper(s, valid, i + 1, path, result)
path.pop() 

C++:

class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
vector<string> res;
string out;
vector<bool> possible(s.size() + 1, true);
wordBreakDFS(s, wordDict, 0, possible, out, res);
return res;
}
void wordBreakDFS(string &s, unordered_set<string> &wordDict, int start, vector<bool> &possible, string &out, vector<string> &res) {
if (start == s.size()) {
res.push_back(out.substr(0, out.size() - 1));
return;
}
for (int i = start; i < s.size(); ++i) {
string word = s.substr(start, i - start + 1);
if (wordDict.find(word) != wordDict.end() && possible[i + 1]) {
out.append(word).append(" ");
int oldSize = res.size();
wordBreakDFS(s, wordDict, i + 1, possible, out, res);
if (res.size() == oldSize) possible[i + 1] = false;
out.resize(out.size() - word.size() - 1);
}
}
}
};

  

类似题目:

[LeetCode] 139. Word Break 单词拆分

All LeetCode Questions List 题目汇总

[LeetCode] 140. Word Break II 单词拆分II的更多相关文章

  1. leetcode 140. Word Break II ----- java

    Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...

  2. Java for LeetCode 140 Word Break II

    Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...

  3. Leetcode#140 Word Break II

    原题地址 动态规划题 令s[i..j]表示下标从i到j的子串,它的所有分割情况用words[i]表示 假设s[0..i]的所有分割情况words[i]已知.则s[0..i+1]的分割情况words[i ...

  4. [LeetCode] 139. Word Break 单词拆分

    Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine ...

  5. leetcode 139. Word Break 、140. Word Break II

    139. Word Break 字符串能否通过划分成词典中的一个或多个单词. 使用动态规划,dp[i]表示当前以第i个位置(在字符串中实际上是i-1)结尾的字符串能否划分成词典中的单词. j表示的是以 ...

  6. Java实现 LeetCode 140 单词拆分 II(二)

    140. 单词拆分 II 给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中.返回所有这些可能的句子. 说明: 分 ...

  7. 140. Word Break II(hard)

    欢迎fork and star:Nowcoder-Repository-github 140. Word Break II 题目: Given a non-empty string s and a d ...

  8. 【LeetCode-面试算法经典-Java实现】【139-Word Break(单词拆分)】

    [139-Word Break(单词拆分)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given a string s and a dictionary of w ...

  9. 【LeetCode】140. Word Break II

    Word Break II Given a string s and a dictionary of words dict, add spaces in s to construct a senten ...

随机推荐

  1. 使用Arduino和LED光柱显示器件轻松制作电池电压指示器

    电池有一定的电压限制,如果电压在充电或放电时超出规定的限制,电池的使用寿命就会受到影响或降低.每当我们使用电池供电的项目,有时我们需要检查电池电压电量,确定是否需要充电或更换.本电路将帮助您监测电池电 ...

  2. 【Audiophobia UVA - 10048 】【Floyd算法】

    题目大意:从a城市到b城市的路径中,尽可能让一路上的最大噪音最小. 题目思路:设d [ i ][ j ]表示 i 到 j 的最大噪音的最小值. 那么d [ i ][ j ] = min( d[ i ] ...

  3. python的tkinter,能画什么图?

    今天从下午忙到现在,睡觉. 这个能绘点图的. import json import tkinter as tk from tkinter import filedialog from tkinter ...

  4. win10设置以管理员身份开机启动

    首先是右键程序,然后设置了管理员权限启动.但是在这样设置之后原先的开机机启动就失效了. 在谷歌之后发现有人通过计划任务开机启动.于是就试了试.别人设置的是用户登录时,我改成了开机就启动.就是这样一改, ...

  5. netstat -an unix socket 会阻塞吗

    [lyd@localhost ~]$ netstat -an | grep "SOFO"unix 2 [ ACC ] SEQPACKET LISTENING 86308 @*MY- ...

  6. jQuery 遍历 - 过滤

    三个最基本的过滤方法是:first(), last() 和 eq(),它们允许您基于其在一组元素中的位置来选择一个特定的元素. 其他过滤方法,比如 filter() 和 not() 允许您选取匹配或不 ...

  7. Dubbo源码分析:ProxyFactory

    roxyFactory将对外开放的服务进行封装.这里使用到代理的方式.ProxyFactory接口有两个不同的实现类:JavassistProxyFactory和JdkProxyFactory.Jdk ...

  8. RMQ问题及ST表

    RMQ(Range Minimum/Maximum Query)问题指的是一类对于给定序列,要求支持查询某区间内的最大.最小值的问题.很显然,如果暴力预处理的话复杂度为 \(O(n^2)\),而此类问 ...

  9. 按位与(&),或(|),异或(^),取反(~),左移(<<),右移(>>)

    C语言提供的位运算符列表:运算符 含义 描述& 按位与 如果两个相应的二进制位都为1,则该位的结果值为1,否则为0| 按位或 两个相应的二进制位中只要有一个为1,该位的结果值为1^ 按位异或 ...

  10. 持续集成学习9 jenkins执行脚本

    一.配置 1.首先在slave节点上写一脚本 [root@node1 script]# cat /application/script/test.sh #!/bin/bash echo "h ...