Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s ="catsanddog",
dict =["cat", "cats", "and", "sand", "dog"].
A solution is["cats and dog", "cat sand dog"].
题意:找出S用dict表示的各种可能。
思路:这题和Word break的区别是上题中,只要考虑是否在的情况,不用考虑各种组合的问题。参考了GeekFans的。其整体思路是,先使用动态规划,找到字符串S中的各种分类,然后使用DFS找到满足条件的各种情况。代码如下:
class Solution {
private:
vector<string> midress;
vector<string> res;
vector<bool> *dp; public:
vector<string> wordBreak(string s, unordered_set<string> &dict)
{ int len=s.size(); dp=new vector<bool>[len];
for(int i=;i<len;++i)
{
for(int j=i;j<len;j++)
{
if(dict.find(s.substr(i,j-i+)) !=dict.end())
dp[i].push_back(true);
else
dp[i].push_back(false);
}
}
dfs(s,len-);
return res;
} void dfs(const string &s,int i)
{
if(i>=)
{
for(int j=;j<=i;++j)
{
if(dp[j][i-j])
{
midress.push_back(s.substr(j,i-j+));
dfs(s,j-);
midress.pop_back();
}
}
return;
}
else
{
string str;
for(int k=midress.size()-;k>=;--k)
{
str+=midress[k];
if(k>)
str+=" ";
}
res.push_back(str);
return;
}
}
};
注:在牛客网通过了,然后一段时间后再次运行时,报错,的结果让我无话可说,见图:
网友Grangyang和Code Gander分别给出不错解法。