一、题目描述
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是
回文串
。返回 s 所有可能的分割方案。
示例 1:
输入:s = “aab”
输出:[[“a”,“a”,“b”],[“aa”,“b”]]
示例 2:
输入:s = “a”
输出:[[“a”]]
提示:
1 <= s.length <= 16
s 仅由小写英文字母组成
链接: 131. 分割回文串
二、参考代码
class Solution {
public:
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>> result;
vector<string> path;
void backtracking(const string& s, int startindex) {
if (startindex == s.size()) {
result.push_back(path);
return;
}
for (int i = startindex; i < s.size(); i++) {
if (isPalindrome(s, startindex, i)) {
string str = s.substr(startindex, i - startindex + 1);
path.push_back(str);
} else {
continue;
}
backtracking(s, i + 1);
path.pop_back();
}
}
vector<vector<string>> partition(string s) {
result.clear();
path.clear();
backtracking(s, 0);
return result;
}
};