https://leetcode.com/problems/word-break-ii/
Given a non-empty string s and a dictionary wordDict containing a list of non-emptywords, 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: []
爲什麼從後往前dp會MLE,從前往後dfs就可以呢?
class Solution {
public:
vector<vector<string>> mem;
vector<bool> visited;
vector<string> wordBreak(string s, vector<string>& wordDict) {
mem = vector<vector<string>>(s.size()+1, vector<string>());
visited = vector<bool>(s.size(), false);
dfs(s, 0, wordDict);
return mem.front();
}
void dfs(string &s, int idx, vector<string> &wordDict){
if(idx == s.size()) return;
if(visited[idx]) return;
for(string cur : wordDict){
if(cur.size() > s.size()-idx) continue;
if(cur != s.substr(idx, cur.size())) continue;
if(idx+cur.size() == s.size()){
mem[idx].push_back(cur);
}else{
dfs(s, idx+cur.size(), wordDict);
for(string bac : mem[idx+cur.size()]){
mem[idx].push_back(cur + " " + bac);
}
}
}
visited[idx] = true;
}
};
class Solution {
public:
vector<vector<string>> dp;
vector<string> wordBreak(string s, vector<string>& wordDict) {
dp = vector<vector<string>>(s.size()+1, vector<string>());
dp[0].push_back("");
for(int i = 0; i < s.size(); ++i){
for(string cur : wordDict){
if(cur.size() > i+1) continue;
if(cur != s.substr(i-cur.size()+1, cur.size())) continue;
if(i-cur.size()+1 == 0){
dp[i+1].push_back(cur);
}else{
for(string pre : dp[i-cur.size()+1]){
dp[i+1].push_back(pre+" "+cur);
}
}
}
}
return dp.back();
}
};
尤其是在"aaaa......aaaaaa",['a', 'aa', 'aaa', ....]這種既不存在無效情況又兩端對稱的樣例下。