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+dfs ,dp来确定每个单词的位置,而dfs则找出所有的句子。
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict)
{
int n = s.length();
vector<vector<int>> next(n);
vector<bool> b(n, false);
//单词尾端位置为n-1的时候需要单独拿出来测试
for(int i = 0; i < n; i++)
{
if(dict.count(s.substr(i, n - i)) != 0)
{
b[i] = true;
next[i].push_back(n - 1);
}
}
//从右往左依次测试符合要求的单词位置
for(int i = n - 1; i >= 0; i--)
{
for(int j = i - 1; j >= 0; j--)
if(b[i] && dict.count(s.substr(j, i - j)))
{
b[j] = true;
next[j].push_back(i - 1);
}
}
string rs;
vector<string> svec;
dfs(0, rs, next, svec, s);
return svec;
}
void dfs(int index, string &rs, vector<vector<int>> &next, vector<string> &svec,
string &target)
{
int n = target.size();
if(index >= n)
{
svec.push_back(rs);
return;
}
int c = next[index].size();
for(int i = 0; i < c; i++)
{
int cursize = rs.size();
rs.insert(rs.end(), target.begin() + index, target.begin() + next[index][i] + 1);
//假如不是最后一个单词 则加空格
if(next[index][i] < n - 1)
rs.push_back(' ');
dfs(next[index][i] + 1, rs, next, svec, target);
rs.resize(cursize);
}
}
};