题目地址: https://leetcode.com/problems/word-break-ii/
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
Example 1:
Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
"cats and dog",
"cat sand dog"
]
Example 2:
Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
[]
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。
说明:
class Solution {
public List wordBreak(String s, List wordDict) {
List res = new ArrayList<>();
wH(res, s, 0, wordDict, "");
return res;
}
public void wH(List res, String s, int index, List words, String cur) {
if (s.length() <= index) {
res.add(cur);
return;
}
for (int i = index + 1; i <= s.length(); i++) {
String temp = s.substring(index, i);
if (!words.contains(temp)) continue;
wH(res, s, i, words, cur.length() == 0 ? temp : (cur + " " + temp));
}
}
}
超出时间限制
class Solution {
public List wordBreak(String s, List wordDict) {
return wH(s, 0, wordDict, new HashMap<>());
}
public List wH(String s, int index, List words, Map> map) {
List res = new ArrayList<>();
if (index >= s.length()) {
return res;
}
if (map.get(index) != null) return map.get(index);
for (int i = index + 1; i <= s.length(); i++) {
String temp = s.substring(index, i);
if (!words.contains(temp)) continue;
if (i == s.length()) {
res.add(temp);
continue;
}
List next = wH(s, i, words, map);
for (int j = 0; j < next.size(); j++) {
res.add(temp + " " + next.get(j));
}
}
map.put(index, res);
return res;
}
}
执行用时:65 ms, 在所有 Java 提交中击败了 19.00% 的用户
内存消耗:39.3 MB, 在所有 Java 提交中击败了 48.73% 的用户