主页有其他数据结构内容(持续更新中)
难度:Medium
代码:
class Solution {
private:
vector<vector<string>> result;
vector<string> path;
bool isPalindrome(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;
}
// 回溯问题都可以抽象为一棵树形结构,通过for循环进行横向遍历,通过递归进行纵向遍历
// startIndex相当于一条切割线,代表下一轮递归遍历的起始位置
void dfs(string s, int startIndex) {
if(startIndex >= s.size()) {
result.emplace_back(path);
return;
}
// for循环遍历的是从startIndex开始,到s.size()-1结束的位置
for(int k = startIndex; k < s.size(); k++) {
// 从startIndex到k位置能构成回文串
if(isPalindrome(s, startIndex, k)) {
string temp = s.substr(startIndex, k - startIndex + 1);
path.emplace_back(temp);
// 由于当前已经找到了从startIndex到k的回文串,因此需要继续寻找以k+1为起点的回文串
dfs(s, k + 1);
// 回溯,将当前插入的string弹出
path.pop_back();
}
// 不是回文串,跳过
else {
continue;
}
}
}
public:
vector<vector<string>> partition(string s) {
dfs(s, 0);
return result;
}
};