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"].
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
vector<bool> dp(s.length() + 1, false);
dp[0] = true;
vector<vector<int>> prev(s.length() + 1);
for (int i = 1; i <= s.length(); i++)
{
for (int j = i - 1; j >= 0; j--)
{
if (dp[j] && dict.count(s.substr(j, i - j)))
{
dp[i] = true;
prev[i].push_back(j);
}
}
}
vector<string> result;
searchSolution(result, prev, s, "", s.length());
return result;
}
void searchSolution(vector<string> &sol, vector<vector<int>> &prev, string &s, string line, int k)
{
if (k == 0)
{
if(line.empty()) return;
line.resize(line.length() - 1); // remove last space character
sol.push_back(line);
return;
}
for (auto j : prev[k])
searchSolution(sol, prev, s, s.substr(j, k - j) + " " + line, j);
}
};
本文详细介绍了如何使用动态规划和回溯法解决字符串拆分问题,即给定一个字符串和一个字典,如何在字符串中插入空格以构成有效的字典单词,并返回所有可能的组合。
1614

被折叠的 条评论
为什么被折叠?



