给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。
说明:
分隔时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:
输入:
s = “catsanddog”
wordDict = [“cat”, “cats”, “and”, “sand”, “dog”]
输出:
[
“cats and dog”,
“cat sand dog”
]
示例 2:
输入:
s = “pineapplepenapple”
wordDict = [“apple”, “pen”, “applepen”, “pine”, “pineapple”]
输出:
[
“pine apple pen apple”,
“pineapple pen apple”,
“pine applepen apple”
]
解释: 注意你可以重复使用字典中的单词。
示例 3:
输入:
s = “catsandog”
wordDict = [“cats”, “dog”, “sand”, “and”, “cat”]
输出:
[]
class Solution {
bool wordBreak2(string s, vector<string> &wordDict) //判断单词是否可以被拆分
{
int len = s.length();
vector<bool> dp(len+1, false); //dp[i]表示字符串s的前i个字符能否拆分成wordDict
int maxLen = 0;
dp[0] = true; //初始化dp[0]为true
for(int i = 0; i <wordDict.size(); i++)
{
maxLen = max(maxLen, (int)wordDict[i].length()); //计算字典中字符串的最大长度
}
for(int i = 1; i <= len; i++)
{
//通常j从0开始,这里做了优化。因为wordDict中的字符串长度是有限的,i-j>maxLen不可能在字典中找到,只需要从i-maxWordLength开始搜索就可以了
for(int j = max(i-maxLen, 0); j < i; j++)
{
if(dp[j] && find(wordDict.begin(), wordDict.end(), s.substr(j, i-j)) != wordDict.end())
{
dp[i] = true;
break;
}
}
}
return dp[len];
}
void dfs(vector<string> &vecRes, vector<string> &vecTmp, vector<string> &wordDict, string s, int index)
{
if(index >= s.length())
{
string strRes = "";
for(int i = 0; i < vecTmp.size()-1; i++)
{
strRes = strRes + vecTmp[i] + " ";
}
strRes += vecTmp[vecTmp.size()-1];
vecRes.push_back(strRes); //这里重新组装
return;
}
for(int i = index; i < s.length(); i++)
{
string strTmp = s.substr(index, i-index+1);
if(find(wordDict.begin(), wordDict.end(), strTmp) != wordDict.end()) //递归回溯
{
vecTmp.push_back(strTmp);
dfs(vecRes, vecTmp, wordDict, s, i+1);
vecTmp.pop_back();
}
}
}
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
vector<string> vecRes;
vector<string> vecTmp;
if(!wordBreak2(s, wordDict)) return vecRes; //这里不先进行判断,会超出时间限制
dfs(vecRes, vecTmp, wordDict, s, 0);
return vecRes;
}
};
判断单词是否拆分用到了动态规划的思想,拆分结果用到了递归回溯的思想