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"]
.
[分析] 最能感受dp剪枝好处的例子:
s="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
dict = ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa",
"aaaaaaaaa","aaaaaaaaaa"]
//////////////////method 3//////////////////// //tag: dp + dfs/backtracking/recursion //dp[i] means s.substring(i, N) satisfy wordBreak //dp[i] |= s.substring(i, j) && dp[j], i < j <=N public List<String> wordBreak(String s, Set<String> dict) { ArrayList<String> result = new ArrayList<String>(); if (dict == null || dict.size() == 0 || s == null || s.length() == 0) return result; int N = s.length(); boolean[] dp = new boolean[N + 1]; dp[N] = true; for (int i = N - 1; i >= 0; i--) { StringBuilder sub = new StringBuilder(s.substring(i, N)); for (int j = N; j >= i; j--) { //dp[i]: s.sub(i, N), sub: s.sub(i, j), dp[j]: s.sub(j, N) dp[i] = dp[j] && dict.contains(sub.toString()); if (dp[i]) break; if (j > i) sub.deleteCharAt(sub.length() - 1); } } if (dp[0]) { StringBuilder item = new StringBuilder(); recur(s, dict, 0, dp, item, result); } return result; } // 使用dp[]进行剪枝, dfs/backtracking/recursion // item = s.sub(0, beg) public void recur(String s, Set<String> dict, int beg, boolean[] dp, StringBuilder item, ArrayList<String> result) { if (beg == s.length()) { item.deleteCharAt(item.length() - 1); result.add(item.toString()); return; } for (int i = beg + 1; i <= s.length(); i++) { String sub = s.substring(beg, i); if(dict.contains(sub)&& dp[i]) { int oldLength = item.length(); item.append(sub).append(' '); recur(s, dict, i, dp, item, result); item.delete(oldLength, item.length()); } } } /////////////////////method 2//////////////////// /* Time Limit Exceeded public List<String> wordBreak(String s, Set<String> dict) { ArrayList<String> result = new ArrayList<String>(); if (s == null || s.length() == 0) return result; int N = s.length(); boolean[] dp = new boolean[N + 1]; ArrayList<ArrayList<StringBuilder>> data = new ArrayList<ArrayList<StringBuilder>>(N + 1); dp[0] = true; ArrayList<StringBuilder> data0 = new ArrayList<StringBuilder>(); data0.add(new StringBuilder()); data.add(data0); for (int i = 1; i <= N; i++) { data.add(new ArrayList<StringBuilder>()); StringBuilder sub = new StringBuilder(s.substring(0, i)); for (int j = 0; j < i; j++) { if (dp[j] && dict.contains(sub.toString())) { dp[i] = true; for (StringBuilder sb : data.get(j)) { StringBuilder copy = new StringBuilder(sb.toString()); copy.append(sub.toString()).append(' '); data.get(i).add(copy); } } sub.deleteCharAt(0); } } for (StringBuilder sb : data.get(N)) { sb.deleteCharAt(sb.length() - 1); result.add(sb.toString()); } return result; } */ //////////////////method 1///////////////////// /* Time Limit Exceeded public List<String> wordBreak(String s, Set<String> dict) { ArrayList<String> result = new ArrayList<String>(); if(s == null || s.length() == 0) return result; recur(s, dict, 0, new StringBuilder(), result); return result; } // 太多冗余计算 public void recur(String s, Set<String>dict, int start, StringBuilder item, ArrayList<String> result) { if(start == s.length()) { item.deleteCharAt(item.length() - 1); result.add(item.toString()); return; } for (int i = start; i < s.length(); i++) { String sub = s.substring(start, i + 1); if (dict.contains(sub)) { int oldLength = item.length(); item.append(sub).append(' '); recur(s, dict, i + 1, item, result); int newLength = item.length(); item.delete(oldLength, newLength); } } } */ }
相关推荐
javascript js_leetcode题解之140-word-break-ii.js
python python_leetcode题解之140_Word_Break_II
javascript js_leetcode题解之139-word-break.js
python python_leetcode题解之139_Word_Break
lru缓存leetcode Go 中解决的一些 Leetcode 问题 大批 3sum-0015 买卖股票的最佳时机-0121 最多水的容器-0011 contains-duplicate-0217 find-minimum-in-rotated-sorted-array-0153 ...word-break-0139 图形
在提供的代码库"WordBreak-Leetcode-139-master"中,你可能会找到一个具体的实现,它可能包括以下部分: - 主函数,接收字符串sentence和词汇表wordDict作为输入参数。 - 动态规划的逻辑,包括初始化dp数组和遍历...
leetcode 苹果断字 给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,确定 s 是否可以被分割成一个或多个字典单词的空格分隔序列。 笔记: 字典中的同一个词可能会在切分中重复使用多次。...word. E
扩展矩阵leetcode Leetcode Leetcode Answer-Java 数组 11.乘最多水容器 ...wordBreak 279.完全平方数 numSquares 排序 56.合并区间 merge 75.颜色分类 sortColors 179.最大数 largestNumber 324.摆
5. Word Break II 单词断词II是一个变体的问题,要求将字符串断词为单词,并且可以使用动态规划或Trie树来解决该问题。 6. Word Ladder 单词梯是一个字符串问题,要求将一个单词转换为另一个单词,并且每次转换...
137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [C++](./C++/single-number-ii.cpp) [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium ||| 190 | [Reverse Bits]...
preorder-traversal链表reorder-list链表linked-list-cycle-ii链表linked-list-cycle动态规划word-break-ii动态规划word-break链表copy-list-with-random-pointer复杂度single-number-ii复杂度single-number动态规划
function wordBreak(s, wordDict) { const dp = Array(s.length + 1).fill(false); dp[0] = true; for (let i = 1; i ; i++) { for (const word of wordDict) { if (s.startsWith(word, i - word.length) && ...
第 338 章概括 [(雅虎)4。...问题/数组和字符串/140.word_break_ii.md) [151. 反转字符串中的单词](Leetcode Problems/Array and String/151.reverse_words_in_a_string.md) [167. Two Sum 2 - In
断字leetcode 断字 “断字”问题的解决方案。 用 C# 编写 Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. ...
* Word Break、Word Break II:该题目要求将字符串分割成单词,实现方法使用了动态规划和回溯算法。 * Word Ladder:该题目要求将一个单词转换成另一个单词,实现方法使用了广度优先搜索算法。 二、树和图 * ...
leetcode 530 力扣在线评委 # 问题 困难 解决方案 1 简单的 2 中等的 3 中等的 12 中等的 22 中等的 39 中等的 94 中等的 108 中等的 122 中等的 136 中等的 144 中等的 167 中等的 238 中等的 260 中等的 268 中等...
- **Word Break**:判断一个字符串是否可以拆分为一个词汇表中的单词序列。 7. **链表(Linked List)**: - **Linked List Cycle**:检测链表中的环。 - **Remove Duplicates from Sorted List**:从已排序的...
def wordBreak(s, wordDict): wordDict = set(wordDict) # 将单词列表转换为集合,加快查找速度 dp = [False] * (len(s) + 1) # 初始化动态规划数组,dp[i]表示s[:i]是否可以被拆分 dp[0] = True # 空字符串可以...
Word Break II 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. Example Example 1...
leetcode 【演示记录】 报告 展示 2017/03/06 1.二和,167.二和二 2107/03/06 15.3 总和,16.3 总和最近,18.4 总和,11.最多水的容器 2017/03/09 62.Unique Paths, 63.Unique Paths II, 64.Minimum Path Sum 2017/...