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表示的是以 ...
随机推荐
- Android中各种onTouch事件
Android里有两个类 android.view.GestureDetector android.view.GestureDetector.SimpleOnGestureListener 1) 新建 ...
- C# 约瑟夫环算法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- Highcharts 点击反选
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...
- Unity 对象池的使用
在游戏开发过程中,我们经常会遇到游戏发布后,测试时玩着玩着明显的感觉到有卡顿现象.出现这种现象的有两个原因:一是游戏优化的不够好或者游戏逻辑本身设计的就有问题,二是手机硬件不行.好吧,对于作为程序员的 ...
- C# 中文转拼音类
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SU { ...
- silverlight visifire控件图表制作——silverlight 后台方法画图
1.调用wcf 获取信息 private void svc_GetSingleChartDataCompleted(object sender, GetSingleChartDataCompleted ...
- 决策树简单介绍(二) Accord.Net中决策树的实现和使用
决策树介绍 决策树是一类机器学习算法,可以实现对数据集的分类.预测等.具体请阅读我另一篇博客(http://www.cnblogs.com/twocold/p/5424517.html). Accor ...
- jaxb xml to bean
package www.garbin.com.utils; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException ...
- 基于注释的Spring Security实战
一.准备工作 预准备的工具及软件有: 1. Eclipse IDE:我使用Eclipse JEE 3.7版,即eclipse-jee-indigo-SR2-win32-x86_64.zip 2. JD ...
- hdu1054 树状dp
B - 树形dp Crawling in process... Crawling failed Time Limit:2000MS Memory Limit:10000KB 64bit ...