算法训练营第二十七天
回溯算法day03
39. 组合总和
这道题可以重复使用元素,因此把回溯函数的startindex改成i就行.
class Solution {
public:
void backtracing(int startindex,int curSum,vector<int> candidates,int target) {
if (curSum > target) {
return;
}
if (curSum == target) {
res.push_back(path);
return;
}
for (int i = startindex; i < candidates.size(); i++) {
path.push_back(candidates[i]);
curSum += candidates[i];
backtracing(i, curSum, candidates, target);
path.pop_back();
curSum -= candidates[i];
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
backtracing(0, curSum, candidates, target);
return res;
}
private:
vector<int>path;
vector<vector<int>> res;
int curSum = 0;
};
40.组合总和II
这道题的候选人集合的元素可以重复。因此需要去重,需要加一个vector<int>used
标记使用过的元素。
class Solution {
public:
void backtracing(int curSum,int startIndex, const vector<int>& candidates, int target, vector<bool> used) {
if (curSum > target)
return;
if (curSum == target) {
res.push_back(path);
return;
}
for (int i = startIndex; i < candidates.size()&& curSum + candidates[i] <= target; i++) {
if (i > 0 && candidates[i] == candidates[i - 1] && used[i-1]==false) {
continue;
}
path.push_back(candidates[i]);
used[i] = true;
curSum += candidates[i];
backtracing(curSum, i + 1, candidates, target, used);
path.pop_back();
used[i] = false;
curSum -= candidates[i];
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<bool> used(candidates.size(), false);
if(candidates[0]>target)
return res;
while (candidates.back() > target) {
candidates.pop_back();
}
backtracing(0, 0, candidates, target,used);
return res;
}
private:
vector<vector<int>>res;
vector<int> path;
};
131.分割回文串
这道题没看解析我居然自己写出来了,真的成就感满满,我觉得我能做出来就是因为我画了图,画完图之后,用回溯法的三部曲
1、定输入输出:这个先不急,后面需要什么就再加
2、终止条件:如果path有两个及以上的元素,且倒数第二个元素不是回文串,则终止。
3、定单次循环的逻辑:首先如果path的后两个元素都是回文串,则存入结果。其次再定for循环和path的push和pop
class Solution {
public:
bool isHuiWen(string s) {
for (int i = 0, j = s.size() - 1; i < j; i++, j--) {
if (s[i] != s[j])
return false;
}
return true;
}
void backtracing(vector<string> path) {
if (path.size()!=1&&!isHuiWen(*(path.end() - 2))) {
return;
}
if (path.size() == 1&&isHuiWen(path.back())) {
res.push_back(path);
}
if (path.size() != 1&&isHuiWen(*(path.end() - 2)) && isHuiWen(*(path.end() - 1))) {
res.push_back(path);
}
for (int i = 1; i < path.back().size(); i++) {
string tmp = path.back();
path.pop_back();
path.push_back(tmp.substr(0, i));
path.push_back(tmp.substr(i, tmp.size() - i));
backtracing(path);
path.pop_back();
path.pop_back();
path.push_back(tmp);
}
}
vector<vector<string>> partition(string s) {
vector<string> path;
path.push_back(s);
backtracing(path);
return res;
}
private:
vector<vector<string>>res;
};
我的方法在时间复杂度和空间复杂度上都过高,代码随想录的方法更好,它是用了双指针,当判断是回文的时候才会存入path,然后收集叶子结点。