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:
[]
链接:https://leetcode.com/problems/word-break-ii/description/
题解:动态规划,主要用dp数组记录递归状态,转移方程:定义状态s中前i个字符串所对应的可能句子dp[i]={dp[j-1]+str[j:i]}其中str[j:i]为字典中单词,把所有满足结果都遍历一遍就是答案,注意这里要用map记录每个i所对应的结果即记忆化搜索,也可以定义为从末尾到第i个,这里第一次提交错误是分界处j-1没有用-1还有需要考虑边界情况即整个都是str单词直接加入res中
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
map<int,vector<string>> mp;
unordered_set<string> dict;
for(auto str:wordDict){
dict.insert(str);
}
vector<string> ans=dfs(s,dict,mp,0);
return ans;
}
vector<string> dfs(string s,unordered_set<string> dict, map<int,vector<string>>& mp,int index){
if(mp.find(index)!=mp.end()) return mp[index];
vector<string> res;
for(int i=index+1;i<=s.size();i++){
string str=s.substr(index,i-index);
if(dict.find(str)!=dict.end()){
if(i==s.size()) res.push_back(str);
vector<string> tmp=dfs(s,dict,mp,i);
for(auto ss:tmp){
res.push_back(str+' '+ss);
}
}
}
mp[index]=res;
return res;
}
};
还可以进一步优化设置一个flag数组来标记改处无法继续分割完成剪枝