难度:中等
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]
题目分析:
显然使用回溯算法,将所有分割的可能都尝试一遍,并且判断字符串是否为回文字符串进行剪枝。
结束条件:当index == n时,所有字符分割完成时
all station:for循环,全局变量index,每次从index开始遍历,将当前的i+1作为index传入下次递归,因为每次的分割都是在上一次分割的基础上进行的。每次递归前需要检测当前的字符串是否是回文字符串,否则的话不分割。
参考代码:
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
if (s.empty())
return res;
vector<string> temp;
back_search(res, temp, s, 0, s.size());
return res;
}
void back_search(vector<vector<string>>& res, vector<string> temp, string s, int index, int n)
{
//结束条件
if (index == n)
{
res.push_back(temp);
}
else{
for (int i = index; i < s.size(); i++)
{
if (check(s, index, i))
{
temp.push_back(s.substr(index, i + 1 - index));
back_search(res, temp, s, i + 1, n);
temp.pop_back();
}
}
}
}
bool check(const string&s, int i, int j)
{
if (j < i) return true;
if (s[i++] == s[j--]) return check(s, i, j);
else return false;
}
};