Word Break II 解答
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 解答的更多相关文章
- 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 ...
- 【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 ...
- 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 ...
- 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 ...
- 【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 ...
- [Leetcode Week9]Word Break II
Word Break II 题解 题目来源:https://leetcode.com/problems/word-break-ii/description/ Description Given a n ...
- 【Word Break II】cpp
题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...
- 140. Word Break II(hard)
欢迎fork and star:Nowcoder-Repository-github 140. Word Break II 题目: Given a non-empty string s and a d ...
- leetcode 139. Word Break 、140. Word Break II
139. Word Break 字符串能否通过划分成词典中的一个或多个单词. 使用动态规划,dp[i]表示当前以第i个位置(在字符串中实际上是i-1)结尾的字符串能否划分成词典中的单词. j表示的是以 ...
随机推荐
- ZOJ3765---Lights (Splay伸展树)
Lights Time Limit: 8 Seconds Memory Limit: 131072 KB Now you have N lights in a line. Don't wor ...
- EL表达式使用之类switch语句
http://blacksonny.iteye.com/admin/blogs/1879878
- 源码分析之struts1自定义方法的使用与执行过程
最近有人问我,你做项目中用户的一个请求是怎么与struts1交互的,我说请求的url中包含了action的名字和方法名,这样就可以找到相应方法,执行并返回给用户了. 他又问,那struts1中有什么方 ...
- 【Cocos2d-X开发学习笔记】第19期:动作管理类(CCActionManager)的使用
本系列学习教程使用的是cocos2d-x-2.1.4(最新版为3.0alpha0-pre) ,PC开发环境Windows7,C++开发环境VS2010 一.动作管理类 动作管理类CCActionMan ...
- 【技术文档】《算法设计与分析导论》R.C.T.Lee等·第7章 动态规划
由于种种原因(看这一章间隔的时间太长,弄不清动态规划.分治.递归是什么关系),导致这章内容看了三遍才基本看懂动态规划是什么.动态规划适合解决可分阶段的组合优化问题,但它又不同于贪心算法,动态规划所解决 ...
- [Angular 2] Injecting a Service
Using Services in Angular 2 is very simple. This lesson covers how to create a simple class as a Ser ...
- 随着时间的推移:构造SDK路径错误(An error occurred while automatically activating bundle com.android.ide.eclipse.adt)
在进行Android应用的开发过程中,有时候在配置SDK路径的时候(Windows->Preferences->Android).会出现例如以下报错:An error occurred w ...
- jquery获取当前元素坐标
1. jquery获取当前元素坐标 A) 获取对象
- 安装oracle11g未找到文件WFMLRSVCApp.ear文件
win7_64位系统,安装oracle11gR2时,报错提示: 未找到文件...WFMLRSVCApp.ear文件 解决方法如下: 将下载的两个压缩包解压至同一目录(合并)再安装即可解决此类问题.
- 需求管理(REQM,Requirements Management)工具(转)
需求管理(REQM,Requirements Management)属于成熟度2级(受管理级)的过程域,是其他许多过程域实施的前提.对于暂未实施CMMI的企业,同样也可以借鉴CMMI的原则,实施和优化 ...