1、组合总和
组合总和
class Solution {
public:
vector<int> path;
vector<vector<int>> result;
void backtracking(vector<int>& candidates, int target, int startIndex) {
if (target < 0) return ;
if (target == 0) {
result.push_back(path);
return ;
}
for (int i = startIndex; i < candidates.size(); i++) {
path.push_back(candidates[i]);
backtracking(candidates, target - candidates[i], i);
path.pop_back();
}
return ;
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
backtracking(candidates, target, 0);
return result;
}
};
2、组合总和 II
组合总和 II
class Solution {
public:
vector<int> path;
vector<vector<int>> result;
void backtracking(vector<int>& candidates, int target, int startIndex, vector<bool> used) {
if (target < 0) return ;
if (target == 0) {
result.push_back(path);
return ;
}
for (int i = startIndex; i < candidates.size(); i++) {
if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) continue;
used[i] = true;
path.push_back(candidates[i]);
backtracking(candidates, target - candidates[i], i + 1, used);
path.pop_back();
used[i] = false;
}
return ;
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<bool> used(candidates.size(), false);
backtracking(candidates, target, 0, used);
return result;
}
};
3、分割回文串
分割回文串
class Solution {
public:
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;
}
void backtracking(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();
}
}
vector<vector<string>> partition(string s) {
backtracking(s, 0);
return result;
}
};