LeetCode Word Break II

时间:2021-11-28 10:50:35

原题链接在这里: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:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

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:
[]

题解:

When it needs all the possible results, it comes to dfs.

Could use memo to prune branches. Use memo means divide and conquer, not iterative.

If cache already has key s, then return list value.

Otherwise, get either head or tail of s, check if it is in the wordDict. If yes, put the rest in the dfs and get intermediate result.

Iterate intermediate result, append each candidate and add to res.

Update cache and return res.

Note: When wordDict contains current s, add it to res. But do NOT return. Since it may cut more possibilities.

e.g. "dog" and "dogs" are both in the result. If see "dogs" and return, it cut all the candidates from "dog".

Time Complexity: exponential.

Space: O(n). stack space O(n).

AC  Java:

 class Solution {
Map<String, List<String>> cache = new HashMap<>();
public List<String> wordBreak(String s, List<String> wordDict) {
List<String> res = new ArrayList<>(); if(s == null || s.length() == 0){
return res;
} if(cache.containsKey(s)){
return cache.get(s);
} if(wordDict.contains(s)){
res.add(s);
} for(int i = 1; i<s.length(); i++){
String tail = s.substring(i);
if(wordDict.contains(tail)){
List<String> cans = wordBreak(s.substring(0, i), wordDict);
for(String can : cans){
res.add(can + " " + tail);
}
}
} cache.put(s, res);
return res;
}
}

类似Word Break.