给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]
思路分析:采取回溯法。 如果当前分割的小段为回文串,继续在后面剩余的尝试分割,否则扩大当前的分割长度,判断是否是回文串。
class Solution {
public:
vector<string> tempRes;
vector<vector<string>> result;
vector<vector<string>> partition(string s) {
if (s == "") {
return result;
}
dfs(s, 0);//开始搜索
return result;
}
//从beginIndex开始,寻找回文子串
void dfs(string &str, int beginIndex) {
int strSize = str.size();
if (beginIndex == strSize) {//如果截取到了尾端,说明寻找到了一个解
result.push_back(tempRes);
return;
}
//对截取长度进行穷举
for (int endIndex = beginIndex; endIndex < strSize; ++endIndex) {
if (isPalindrome(str, beginIndex, endIndex)) {//如果当前截取的[beginIndex, endIndex]段是回文串
string strTemp = str.substr(beginIndex, endIndex - beginIndex + 1);//截这个子串
tempRes.push_back(strTemp);//放入中间结果
dfs(str, endIndex + 1);//以endIndex + 1下标为起始,继续寻找
tempRes.pop_back();//当使用完后,需要将前面放入的段pop
}
}
}
//判断在str串中截取[beginIndex, endIndex]段是否是回文串
bool isPalindrome(string &str, int beginIndex, int endIndex) {
while (beginIndex < endIndex) {
if (str[beginIndex++] != str[endIndex--]) {
return false;
}
}
return true;
}
};