day23 回溯2
39. 组合总和
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtracking(int target, int index, vector<int> &candidates) {
if (target == 0) {
res.push_back(path);
}
if (target <= 0) {
return;
}
for (int i = index; i < candidates.size(); i ++) {
path.push_back(candidates[i]);
backtracking(target-candidates[i], i, candidates);
path.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
backtracking(target, 0, candidates);
return res;
}
};
40.组合总和II
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtracking(vector<int> &candidates, int target, int index) {
if (target < 0) {
return;
}
if (target == 0) {
res.push_back(path);
return;
}
for (int i = index; i < candidates.size(); i ++) {
if (i > index && candidates[i] == candidates[i-1]) {
continue;
}
path.push_back(candidates[i]);
backtracking(candidates, target - candidates[i], i + 1);
path.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0);
return res;
}
};
131.分割回文串
class Solution {
public:
vector<vector<string>> res;
vector<string> path;
bool isTrue(string s, int left, int right) {
for (int i = left, j = right; i < j; i ++, j --) {
if (s[i] != s[j]) {
return false;
}
}
return true;
}
void backtracking(const string &s, int index) {
if (index >= s.size()) {
res.push_back(path);
return;
}
for (int i = index; i < s.size(); i ++) {
if (isTrue(s, index, i)) {
string str = s.substr(index, i - index + 1);
path.push_back(str);
backtracking(s, i + 1);
path.pop_back();
}
}
}
vector<vector<string>> partition(string s) {
backtracking(s, 0);
return res;
}
};