Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
DFS:
void dfs(string s, vector<string> &path, vector<vector<string>> &res)
{
if(s.size() < 1)
{
res.push_back(path);
return;
}
for(int i = 0; i < s.size(); i++)
{
int begin = 0;
int end = i;
while(begin < end)
{
if(s[begin] == s[end])
{
begin++;
end--;
}
else
break;
}
if(begin >= end)//bool isPalindrome = true;
{
path.push_back(s.substr(0,i+1));
dfs(s.substr(i+1),path,res);
path.pop_back();
}
}
}
vector<vector<string>> partition(string s) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<vector<string>> res;
vector<string> path;
dfs(s,path,res);
return res;
}

本文介绍了一种使用深度优先搜索(DFS)实现的算法,该算法可以找出所有可能的回文字符串分割方式。通过递归地检查子串是否为回文,并在找到有效分割时记录结果,最终返回所有可行的分割方案。
347

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



