给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
示例 1:
输入:s = “aab”
输出:[[“a”,“a”,“b”],[“aa”,“b”]]
示例 2:
输入:s = “a”
输出:[[“a”]]
提示:
1 <= s.length <= 16
s 仅由小写英文字母组成
class Solution {
public:
vector<vector<string>> res; // 存储结果
vector<string> path; // 存储每条路径上面的所有的回文子串
bool isPalindrome(string& s, int st, int end) { // 判断是否是回文
for (int i = st, j = end; i < j; i++, j--) {
if (s[i] != s[j])
return false;
}
return true;
}
void backtracking(string& s, int index) {
if (index >= s.size()) { // 代表切割到末尾了
res.push_back(path);
return;
}
for (int i = index; i < s.size(); i++) {
if (isPalindrome(s, index, i)) {
// [index,i] 是回文子串
string str = s.substr(index, i - index + 1);
path.push_back(str);
} else {// 子串不是回文就跳过
continue;
}
backtracking(s, i + 1); // 因为本身自能使用一次,要不断向后切割,所以 i + 1
path.pop_back();
}
}
vector<vector<string>> partition(string s) {
res.clear();
path.clear();
if (s.size() == 1) {
path.push_back(s);
res.push_back(path);
return res;
}
backtracking(s, 0); // 回溯,字符串s 和 切割点index
return res;
}
};