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. 潘石屹的SOHO小报猝死

    东莞时报多媒体数字报刊平台 潘石屹的SOHO小报猝死

  2. qq2013 java版(完整工程源码 包含服务端 oracle数据库)毕业设计有用

    /** * 初始化组件 */ private void initComponent() { //提示面板 errorTipPane = new ErrorTipPane(); // 主面板 mainP ...

  3. Ext.window的close的问题

    以前每次都是用的hide,关闭后隐藏窗体,下一次点击再打开,这种方法在我的随笔里面有,可是现在遇到一个问题,我的窗体里面有个formpanel,formpanel每一项都有一个默认值,意思就是修改的时 ...

  4. 关于bootstrap--网格系统

    1. 2.偏移列(col-md-offset-*):为了在大屏幕显示器上使用偏移,请使用 .col-md-offset-* 类.这些类会把一个列的左外边距(margin)增加 * 列,其中 * 范围是 ...

  5. MyBatis初学者配置

    小配置 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC &qu ...

  6. 布局神器:Flexbox

    最近的工作内容大多是移动端网页的开发,百分比布局,Media Queries,Bootstrap等常规的响应式/自适应的开发技术皆一一试过,但觉以上都不够灵活,所以,一直再尝试寻求更加灵活的精确的移动 ...

  7. HDOJ 1316 How Many Fibs?

    JAVA大数.... How Many Fibs? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Jav ...

  8. python 间谍程序传输文件 socket编程

    本程序实现了,把目标机器的某个目录(可控)的所有的某种类型文件(可控)全部获取并传到己方的机器上. 1.用了base64的encode(infile,outfile)加密,以及decode(infil ...

  9. [.NET | 發佈] 如何指定固定的目錄給程式調用的外部DLL?

    1.OverView 一般程式只會查找與主程式同目錄的DLL檔案 解決方案主要可以參考這篇:http://support.microsoft.com/kb/837908 2.實作app.config方 ...

  10. Javascript的块级作用域

      一.块级作用域的说明 在学习JavaScript的变量作用域之前,我们应当明确几点: a.JavaScript的变量作用域是基于其特有的作用域链的. b.JavaScript没有块级作用域. c. ...