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表示的是以 ...
随机推荐
- openSourceEvent
开放源码(开源)的精神在于使用者可以使用.复制.散布.研究和改进软件.这可以追溯到20世纪60年代,至今已有半个世纪了.虽然下面所列举的不都是专门的开源产品,但还是在开源发展的进程中有着巨大的影响. ...
- Swift 2.0初探:值得注意的新特性
转眼间,Swift已经一岁多了,这门新鲜.语法时尚.类型安全.执行速度更快的语言已经渐渐的深入广大开发者的心.我同样也是非常喜爱这门新的编程语言. 今年6月,一年一度的WWDC大会如期而至,在大会上A ...
- js方法调用
<!DOCTYPE html> <html> <head> <title>测试</title> </head> <body ...
- Linq中的多表左联,详细语句
from m in context.WX_MemberCollectDish join d in context.Dish on m.DishID equals d.DishID into temp ...
- sql server windows账号不能登陆指定的数据库
问题描述: 1. windows账号登陆后,默认的数据库被删除 2. SA账号密码也忘记了 此时就会导致用windows账号登陆Sql Server的时候,返回4064的错误,按照上面的问题描述,应该 ...
- BZOJ4006 JLOI2015 管道连接(斯坦纳树生成森林)
4006: [JLOI2015]管道连接 Time Limit: 30 Sec Memory Limit: 128 MB Description 小铭铭最近进入了某情报部门,该部门正在被如何建立安全的 ...
- 探索A@1db9742
public class S { /** * @param args */ public static void main(String[] args) { System.out.printl ...
- poj3579 二分搜索+二分查找
Median Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 5468 Accepted: 1762 Descriptio ...
- C语言中的指针数组和数组指针
代码: #include <iostream> using namespace std; int main(){ ]; ]; cout<<sizeof(a)<<en ...
- [总结]Map: C++ V.S. Java
整理一下Map在Java 和 C++的基本操作,欢迎大家一起交流学习. 附: 对于在C++中,选用map 还是 unordered_map,可以参考这篇讨论.相对简单粗暴的结论是,unordered_ ...