目录
题目:
代码(首刷看解析 2024年2月3日):
class Solution {
public:
vector<vector<string>> res;
vector<string> path;
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;
}
void backtracking(const string& s, int startIndex) {
if (startIndex >= s.size()) {
res.push_back(path);
return;
}
for (int i = startIndex; i < s.size(); ++i) {
if (isPalindrome(s, startIndex, i)) {
string str = s.substr(startIndex, i + 1 - startIndex);
path.push_back(str);
} else {
continue;
}
backtracking(s, i + 1);
path.pop_back();
}
return;
}
vector<vector<string>> partition(string s) {
if (s.size() == 0) return res;
backtracking(s, 0);
return res;
}
};
代码(二刷自解 debug了蛮久的 2024年3月8日)
class Solution {
public://回溯
vector<vector<string>> result;
vector<string> paths;
// 检查是否是回文
bool check(const string& str) {
int left = 0, right = str.size() - 1;
while (left < right) {
if (str[left] != str[right]) return false;
left++;
right--;
}
return true;
}
void backtracking(string s, int startIndex, int length) {
//返回条件:paths装满所有s中的字母
if (length == s.size()) {
result.push_back(paths);
return;
}
// 遍历 note:每多遍历一次,字串长度+1 遇见不符合子串剪枝
for (int i = startIndex; i < s.size(); ++i) {
string temp = s.substr(startIndex, i - startIndex + 1);
// 剪枝
if (!check(temp)) continue;
// 更新paths
paths.push_back(temp);
// 递归
backtracking(s, i + 1, length + (i - startIndex + 1));
// 回溯
paths.pop_back();
}
}
vector<vector<string>> partition(string s) {
if (s.size() == 0) return result;
backtracking(s, 0, 0);
return result;
}
};
代码(三刷看解析 2024年5月22日)
回溯递归那里没想清楚看了解析,可以将for循环考虑成横着切字符串,递归考虑成在树枝上切字符串
class Solution {
public:
vector<vector<string>> res;
vector<string> path;
bool helper(string str, int left, int right) {
if (left >= right) return true;
while (left < right) {
if (str[left] != str[right]) return false;
left++;
right--;
}
return true;
}
void backtracking(string s, int startIndex) {
// 符合条件,加入结果集
if (startIndex >= s.size()) {
res.push_back(path);
return;
}
// 递归回溯,一层是按大小,一树枝是按个数
for (int i = startIndex; i < s.size(); i++) {
if (helper(s, startIndex, i)) {
auto temp = s.substr(startIndex, i - startIndex + 1);
path.push_back(temp);
} else {
continue;
}
backtracking(s, i + 1);
path.pop_back();
}
}
vector<vector<string>> partition(string s) {
backtracking(s, 0);
return res;
}
};