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"]
.
其实我觉得这题很难,对于菜鸟来说,也是理解别人的代码理解了两天才弄明白,对于动态规划,一直都不是很会用,这里,把我理解的深入地表示一下。其中,dp[i][j]表示从i到j的字符串是否在字典中。
这是以题目举得一个例子,此张表中的0,1就是dp的表示,红框和绿框表示第一轮和第二轮寻找(从下往上)。具体代码和注释如下,解释很麻烦,希望可以看懂:
class Solution {
public:
vector<bool>*dp;
vector<string>mystring;
vector<string>result;
vector<string> wordBreak(string s, unordered_set<string> &dict){
dp = new vector<bool>[s.size()]; //定义一个二维数组
for (int i = 0;i<s.size();i++)
{
for (int j = i;j<s.size();j++)
{
if (dict.find(s.substr(i,j-i+1))!=dict.end()) //在字典中一次查找此单词是否存在
dp[i].push_back(true);
else
dp[i].push_back(false);
}
}
Output(s.size()-1,s); //将存在的单词按照句子的形式表示出来,我觉得这才是最难的地方
return result;
}
void Output(int index,string s)
{
if(index == -1) //如果索引值为-1,也就是说上一个单词已经从0开始了,那么就要组合找到的单词
{
string str;
for (int i = mystring.size()-1;i>=0;i--) //组合比较简单
{
str += mystring[i];
if (i!=0)