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. 学完 JAVA SE后学什么 。。。

    我觉得学习j2ee一定要循序渐进,千万不要太急了.把java基础打牢一点,再牢一点.各位,你们在后面学习什么 struts,hibernate,spring,ajax..都很轻松. 第一个阶段(jav ...

  2. 【hoj】1604 cable master

    简单,二分法,可是在oj上交的时候会有精度的限制,所以仅仅能把数扩得大一点,并且在扩的时候为防止尾数会自己主动生成一些非零数,所以还是自己吧扩到的位置设置为0,还有输出时由于%.2lf会自己有4设5入 ...

  3. java接口传递数据的实例

    我们要讲E类中的数据变化通知A类,这样通过接口F来实现.具体原理就是E的每次数据改变都让其通知接口:而A类继承接口,所以每次E的调用接口都会触发A类的数据更改事件的触发. 首先创建一个类E: publ ...

  4. unity提取打包资源

    untiy打包资源是不可见的,在代码中须要www载入去提取,当然也有别的方法去提取打包资源.这对于非常久远的数据打包资源来说是个非常好的方法,由于太久远了就找不到了,仅仅能拿打包资源去提取,之前我写过 ...

  5. springmvc4+hibernate4分页查询功能

    Springmvc+hibernate成为现在很多人用的框架整合,最近自己也在学习摸索,由于我们在开发项目中很多项目都用到列表分页功能,在此参考网上一些资料,以springmvc4+hibnerate ...

  6. C++设计模式---Strategy模式

    一.前言 学习的第一个设计模式!不知道理解的对不对,期望大家一起多交流~ Strategy模式:策略模式,定义了算法族,分别封装起来,此模式可以让算法的变化独立于使用算法的客户.Strategy模式将 ...

  7. Ubuntu中设置静态IP和DNS(转载)

    原文地址:http://blog.sina.com.cn/s/blog_669421480102v3bb.html VMware 中使用网络,对虚拟机设置静态IP:在Ubuntu中设置静态IP共两步: ...

  8. oracle得到拼音函数

    CREATE OR REPLACE FUNCTION fgetpy (v_str VARCHAR2)   RETURN VARCHAR2AS   v_strlen   INT;   v_return  ...

  9. iOS_SN_push/pop转场动画封装和一般动画封装

    封装类中的方法: #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface AnimationE ...

  10. OpenGL ES 2.0 符点精度

    片元着色器中使用符点相关类型的变量时与顶点着色器中有所不同,在顶点着色器中直接声明使用即可,而在片元着色器中必须指定精度. lowp 低 mediump 中 highp 高 指定整个着色器中符点相关类 ...