题目链接 : https://leetcode-cn.com/problems/word-break-ii/

题目描述:

给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。

说明:

  • 分隔时可以重复使用字典中的单词。
  • 你可以假设字典中没有重复的单词。

示例:

示例 1:

输入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
输出:
[
"cats and dog",
"cat sand dog"
]

示例 2:

输入:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
输出:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
解释: 注意你可以重复使用字典中的单词。

示例 3:

输入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
输出:
[]

思路:

动态规划:

自顶向下:

参照139. 单词拆分 | 题解链接

相关题型:139. 单词拆分

代码:

思路一:

class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
import functools
if not wordDict:return []
wordDict = set(wordDict)
max_len = max(map(len, wordDict))
@functools.lru_cache(None)
def helper(s):
res = []
if not s:
res.append("")
return res
for i in range(len(s)):
if i < max_len and s[:i+1] in wordDict:
for t in helper(s[i+1:]):
if not t:
res.append(s[:i+1])
else:
res.append(s[:i+1] + " " + t)
return res
return helper(s)

java

class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
int max_len = 0;
for (String word : wordDict) max_len = Math.max(max_len, word.length());
return helper(s, max_len, wordDict, new HashMap<String, LinkedList<String>>());
} private List<String> helper(String s, int max_len, List<String> wordDict, HashMap<String, LinkedList<String>> cache) {
if (cache.containsKey(s)) return cache.get(s);
LinkedList<String> res = new LinkedList<>();
if (s.length() == 0) {
res.add("");
return res;
}
for (int i = 0; i < s.length(); i++) {
if (i < max_len && wordDict.contains(s.substring(0, i + 1))) {
for (String tmp : helper(s.substring(i + 1), max_len, wordDict, cache))
res.add(s.substring(0, i + 1) + (tmp.isEmpty() ? "" : " ") + tmp);
}
}
cache.put(s, res);
return res;
}
}

最新文章

  1. 学习OpenStack之 (4): Linux 磁盘、分区、挂载、逻辑卷管理 (Logical Volume Manager)
  2. 转帖不会乱码的,powershell网络蜘蛛
  3. CTabCtrl的使用
  4. Windows Media Player axWindowsMediaPlayer1 分类: C# 2014-07-28 12:04 195人阅读 评论(0) 收藏
  5. PHP基础示例:商品信息管理系统v1.1
  6. CDialogSK - A Skinnable Dialog Class
  7. 每天一个linux命令(51)--grep命令
  8. iOS 图片本地存储、本地获取、本地删除
  9. JavaScript的sleep实现--Javascript异步编程学习
  10. CCM和GCM
  11. 修改eclipse的workspace目录
  12. Go开发之路(目录)
  13. xyplorer设置备忘
  14. Excel 2013 表格自用技巧
  15. Summary
  16. The MathType Dll cannot be found 问题解决办法
  17. SQL之分组排序取top n
  18. mac os x 安装mysql 5.7
  19. vmware创建centos虚拟机
  20. hive在客户机启动时出现的问题

热门文章

  1. Python 列表(List)Ⅰ
  2. 4. ClustrixDB CLX命令详解
  3. UVa 11212 Editing a Book (IDA* &amp;&amp; 状态空间搜索)
  4. #424 Div2 Problem C Jury Marks (二分 &amp;&amp; 暴力 &amp;&amp; std::unique &amp;&amp; 思维)
  5. 为什么C++中只有指针和引用才能实现多态?
  6. codevs 1255 搭积木 x
  7. 【gym102394A】Artful Paintings(差分约束系统,二分)
  8. Floating Point Math
  9. Python爬取中文页面的时候出现的乱码问题
  10. mysql-8.0解压缩版安装配置完整过程