39.组合总和
代码如下:
class Solution {
private:
vector<vector<int>> ans; //存放结果
vector<int> path; //存放单次结果
void backtracking(vector<int>& candidates, int startIndex, int target, int sum) {
if (sum > target) {
return;
}
if (sum == target) {
ans.push_back(path);
return;
}
for (int i = startIndex; i < candidates.size(); i++) {
path.push_back(candidates[i]);
sum += candidates[i];
backtracking(candidates, i, target, sum);
sum -= candidates[i]; //这一步很关键!
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
backtracking(candidates, 0, target, 0);
return ans;
}
};
40.组合总和2
代码如下:
class Solution { //不能包含重复的组合,需要去重
private:
vector<vector<int>> ans;
vector<int> path;
void backtracking(vector<int>& candidates, int target, int startIndex, int sum) {
if (sum > target) {
return;
}
if (sum == target) {
ans.push_back(path);
return;
}
for (int i = startIndex; i < candidates.size(); i++) {
if (i > startIndex && candidates[i] == candidates[i - 1]) {
continue;
}
sum += candidates[i];
path.push_back(candidates[i]);
backtracking(candidates, target, i + 1, sum);
sum -= candidates[i];
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0, 0);
return ans;
}
};
131.分割回文串
代码如下:
class Solution {
private:
vector<vector<string>> ans;
vector<string> path;
bool isPalindrome(string str) {
int i = 0;
int j = str.size() - 1;
while (i < j) {
if (str[i] != str[j]) {
return false;
}
i++, j--;
}
return true;
}
void backtracking(string s, int startIndex) {
if (startIndex == s.size()) {
ans.push_back(path);
return;
}
for (int i = startIndex; i < s.size(); i++) {
string temp = s.substr(startIndex, i - startIndex + 1);
if (isPalindrome(temp)) {
path.push_back(temp);
backtracking(s, i + 1);
path.pop_back();
}
}
}
public:
vector<vector<string>> partition(string s) {
backtracking(s, 0);
return ans;
}
};
今毕。