这道题利用vector<bool>来做动态规划,变量名为tmp,tmp的第一个设置为true,从第一个开始遍历,从任何一个true开始,到任何一个地方结束,只要所包含的子串在wordDict里面,就将这个子串的尾部赋值为true,因此,如果tmp最后一个变量为true,则说明这个字符串可以被拆分,否则不行。
class Solution
{
public:
bool inDict(string s, vector<string> wordDict)
{
for (auto x : wordDict)
{
if (x == s)
{
return true;
}
}
return false;
}
bool wordBreak(string s, vector<string>& wordDict)
{
vector<bool> tmp(s.size() + 1, false);
tmp[0] = true;
for (int i = 1; i < s.size() + 1; i++)
{
for (int j = 0; j < i; j++)
{
if (tmp[j] && inDict(s.substr(j, i-j), wordDict))
{
tmp[i] = true;
}
}
}
return tmp.back();
}
};