Description
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:
[]
分析
题目的意思是:给定一个字符串和一个单词字典,把该字符串分成一句子,句子中的每个单词都出现在字典中。
- 这道题既可以用动态规划的方法,也可以用深度优先的方法。终止条件是遍历到字符串s的末尾。
- 循环体为每次截取一个字串来在字典中查找是否存在,存在则继续递归,不存在则继续循环。
代码
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> dict(wordDict.begin(),wordDict.end());
vector<bool> possible(s.size()+1,true);
vector<string> ans;
string item;
dfs(s,0,dict,possible,ans,item);
return ans;
}
bool dfs(string s,int index,unordered_set<string> dict, vector<bool> &possible, vector<string> &ans, string item){
bool res=false;
if(index==s.size()){
ans.push_back(item.substr(0,item.size()-1)); // remove space in the end
return true;
}
for(int i=index;i<s.size();i++){
string word=s.substr(index,i-index+1);
if(dict.find(word)!=dict.end()&&possible[i+1]){
item=item+word+" ";
if(dfs(s,i+1,dict,possible,ans,item)){
res=true;
}else{
possible[i+1]=false;
}
item.resize(item.size()-word.size()-1);
}
}
return res;
}
};