文章目录
- 1.组合总和
- 2.组合总和II
- 3.分割回文串
1.组合总和
参数和返回值:
vector<vector<int>> result;
vector<int> path;
int sum;
void backtracking(vector<int>& candidates, int target, int index)
终止条件:大于等于target;
单层搜索的逻辑:sum求和,递归直到sum>=target。
减枝:sum + candidates[i] <= target
代码如下
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
int sum = 0;
void backtracking(vector<int>& candidates, int target, int index) {
if (sum > target) {
return;
}
if (sum == target) {
result.push_back(path);
return;
}
for (int i = index; i < candidates.size() && sum + candidates[i] <= target; i++) {
sum += candidates[i];
path.push_back(candidates[i]);
backtracking(candidates, target, i);
sum -= candidates[i];
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0);
return result;
}
};
2.组合总和II
跟上一道题
1.组合总和
类似,重点在于数组是有重复的,所以需要对同一树层使用过的元素进行跳过,定义一个vector<bool> used
,记录同一树枝上的元素是否使用过
代码如下
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
int sum;
vector<bool> used;//要对同一树层使用过的元素进行跳过
void backtracking(vector<int>& candidates, int target, int index) {
if (sum > target) {
return;
}
if (sum == target) {
result.push_back(path);
return;
}
for (int i = index; i < candidates.size() && sum + candidates[i] <= target; i++) {
if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
continue;
}
sum += candidates[i];
path.push_back(candidates[i]);
used[i] = true;//要对同一树层使用过的元素进行跳过
backtracking(candidates, target,i + 1);
used[i] = false;
sum -= candidates[i];
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sum = 0;
used = vector<bool>(candidates.size(), false);
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0);
return result;
}
};
3.分割回文串
主要解决两个问题:
1.切割问题,有不同的切割方式
2.判断回文
切割也可以使用回溯法,递归用来纵向遍历,for循环用来横向遍历,切割线(就是图中的红线)切割到字符串的结尾位置,说明找到了一个切割方法。
回溯三部曲
参数和返回值:void backtracking (const string& s, int startIndex)
;
终止条件:切割线到了字符串末尾即终止;
单层搜索逻辑:判断是否回文,是则放入path,不是则跳过
代码如下
class Solution {
private:
vector<vector<string>> result;
vector<string> path;
bool isPalindrome (const string& s, int left, int right) {
while (left < right) {
if (s[left] != s[right]) return false;
left++;
right--;
}
return true;
}
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();
}
}
public:
vector<vector<string>> partition (string s) {
backtracking(s, 0);
return result;
}
};