问题描述:
思路分析:
首先使用动态规划的方法来校验字符串是否可以拆分成字典里的单次,然后使用DFS的方法来获得所有可能的拆分结果。
代码实现:
class Solution {
public:
bool inDict(string s, vector<string> wordDict)
{
for (auto x : wordDict)
{
if (x == s)
{
return true;
}
}
return false;
}
vector<string> wordBreak(string s, vector<string>& wordDict) {
vector<string> answer;
string tempStr = "";
bool result = false;
vector<bool> flag(s.size() + 1, false);
flag[0] = true;
for (int i = 1; i < s.size() + 1; i++)
{
for (int j = 0; j < i; j++)
{
if (flag[j] && inDict(s.substr(j, i - j), wordDict))
{
flag[i] = true;
}
}
}
if (flag[s.size()])
{
DFS(answer, tempStr, s, wordDict);
}
return answer;
}
void DFS(vector<string>& answer, string& record, string s, vector<string>& wordDict)
{
if (s == "")
{
answer.push_back(record);
return;
}
string str;
for (int i = 0; i < wordDict.size(); i++)
{
str = s.substr(0 , wordDict[i].size());
if (str == wordDict[i])
{
string tempStr = record;
record.append(str);
str = s.substr(wordDict[i].size(), s.size() - wordDict[i].size());
if (str != "")
{
record.append(" ");
}
DFS(answer, record, str, wordDict);
record = tempStr;
}
}
}
};