Question

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"].

Solution

这题的基本思路是用recursion,每次都只研究第一刀切在哪儿,然后对剩下的substring做递归。但是我们发现其实可以借助DP的思想,存下来部分中间结果值。这种思想也叫 Memorized Recursion

Memorized recursion并不是一个很好的方法,但是当遇到time limit exceed时可以想到它来拿空间换时间

 class Solution:
# @param s, a string
# @param dict, a set of string
# @return a list of strings
def wordBreak(self, s, dict):
self.dict = dict
# cache stores tmp results: key: substring value: list of results
self.cache = {}
return self.break_helper(s) def break_helper(self, s):
combs = []
if s in self.cache:
return self.cache[s]
if len(s) == 0:
return [] for i in range(len(s)):
if s[:i+1] in self.dict:
if i == len(s) - 1:
combs.append(s[:i+1])
else:
sub_combs = self.break_helper(s[i+1:])
for sub_comb in sub_combs:
combs.append(s[:i+1] + ' ' + sub_comb) self.cache[s] = combs
return combs

第二种思路:先用DP,再用DFS

dp[i] 为list<String>表示以i结尾的在word dict中的词,并且满足dp[i - wordLen]不是null。

DFS从dp[len]开始,遍历可能的词。

 public class Solution {
public List<String> wordBreak(String s, Set<String> wordDict) {
List<String> result = new ArrayList<>();
if (wordDict == null || s == null) {
return result;
}
int len = s.length();
ArrayList<String>[] dp = new ArrayList[len + 1];
dp[0] = new ArrayList<String>();
for (int i = 0; i < len; i++) {
if (dp[i] != null) {
for (int j = i + 1; j <= len; j++) {
String sub = s.substring(i, j);
if (wordDict.contains(sub)) {
if (dp[j] == null) {
dp[j] = new ArrayList<String>();
}
dp[j].add(sub);
}
}
}
}
if (dp[len] == null) {
return result;
}
// dfs
dfs(dp, result, "", len);
return result;
} private void dfs(ArrayList<String>[] dp, List<String> result, String tail, int curPos) {
if (curPos == 0) {
result.add(tail.trim());
return;
}
for (String str : dp[curPos]) {
String curStr = str + " " + tail;
dfs(dp, result, curStr, curPos - str.length());
}
}
}

Word Break II 解答的更多相关文章

  1. LeetCode: Word Break II 解题报告

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

  2. 【leetcode】Word Break II

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

  3. 17. Word Break && Word Break II

    Word Break Given a string s and a dictionary of words dict, determine if s can be segmented into a s ...

  4. LeetCode之“动态规划”:Word Break && Word Break II

     1. Word Break 题目链接 题目要求: Given a string s and a dictionary of words dict, determine if s can be seg ...

  5. 【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 ...

  6. [Leetcode Week9]Word Break II

    Word Break II 题解 题目来源:https://leetcode.com/problems/word-break-ii/description/ Description Given a n ...

  7. 【Word Break II】cpp

    题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...

  8. 140. Word Break II(hard)

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

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

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

随机推荐

  1. Hash Map (Hash Table)

    Reference: Wiki  PrincetonAlgorithm What is Hash Table Hash table (hash map) is a data structure use ...

  2. DHTML【8】--CSS

    在讲HTML时说过,有个Style标签是在CSS里用的,是的,在HTML中添加CSS样式必须要用到Style,在标签里单独定义标签属性时用的是Style属性.上一节我们也说过,先不用管那个Style标 ...

  3. Android Studio:Error:Execution failed for task ':app:mergeDebugResources'. > Some file crunching failed, see logs for details

    Gradle 编译错误: 14:39:58 Executing tasks: [clean, :app:generateDebugSources, :app:mockableAndroidJar, : ...

  4. github atom 试用

    github的编辑器atom 1.0已经出来了,在https://atom.io/ 我之前在win上一直用notepad++写了两年脚本.最近改写lua了,项目组统一用的sublime text.su ...

  5. Chrome浏览器查看cookie

    原文:http://jingyan.baidu.com/article/6b18230954dbc0ba59e15960.html 1. 查看页面的cookie 方法: a). 点击地址栏前面的文档薄 ...

  6. Java 学习第一天

    java 学习路线 http://edu.csdn.net/main/studyline/heimaline.html?flz java 学习视频 —— 马士兵:毕向东

  7. Stm32高级定时器(二)

    Stm32高级定时器(二) 1 主从模式:主?从? 谈论主从,可知至少有两个以上的触发或者驱动信号,stm32内部有多个定时器,可以相互之间驱动或者控制. 主模式:定时器使能只受驱动时钟控制或者输出控 ...

  8. 22个CSS黑魔法

    原链接:http://www.ido321.com/1665.html Hey there! Today we are going to talk about some useful tricks i ...

  9. 自定义VS的ItemTemplates 实现任意文件结构

    上一篇说到重写IHttpHandler实现前后端分离,这次说一下如何建立一个如下文件结构. VS建立webform时是根据模板来的.C#的模板目录如下: F:\Program Files (x86)\ ...

  10. Controller返回值类型ActionResult

    在mvc中所有的controller类都必须使用"Controller"后缀来命名 并且对Action也有一定的要求: 必须是一个public方法 必须是实例方法 没有标志NonA ...