链接
题目
给你一个字符串
s
,请你将s
分割成一些子串,使每个子串都是 回文串 。返回s
所有可能的分割方案。回文串 是正着读和反着读都一样的字符串。
示例
示例 1:
输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]示例 2:
输入:s = "a"
输出:[["a"]]
说明
1 <= s.length <= 16
s
仅由小写英文字母组成
思路
这题切割字符串,其实还是组合问题(如:Leetcode-39. 组合总和),例如对于示例1:aab,组合问题是先选择第一个a,然后再在ab里选a,而该问题则是先再第一个a后面切一刀,然后再ab里a后面再切一刀,切完之后还需要判断是否是回文字符串,否则需要回退,不能这样切割。
C++ Code
class Solution {
public:
vector<vector<string>> res;
vector<string> cur;
void backtracking (const string& s, int startIndex) {
if (startIndex >= s.size()) { res.push_back(cur); return; }
for (int i = startIndex; i < s.size(); i++)
{
if (isPalindrome(s, startIndex, i))
{
string str = s.substr(startIndex, i - startIndex + 1);
cur.push_back(str);
}
else continue;
backtracking(s, i + 1);
cur.pop_back();
}
}
bool isPalindrome(const string& s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--)
{
if (s[i] != s[j]) return false;
}
return true;
}
vector<vector<string>> partition(string s) {
backtracking(s, 0);
return res;
}
};