今日记录
39.组合总和
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& candidates, int target, int sum, int index) {
if (sum > target)
return;
if (sum == target) {
result.push_back(path);
return;
}
for (int i = index; i < candidates.size(); i++) {
sum += candidates[i];
path.push_back(candidates[i]);
backtracking(candidates, target, sum, i);
sum -= candidates[i];
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
result.clear();
path.clear();
backtracking(candidates, target, 0, 0);
return result;
}
};
40.组合总和Ⅱ
难点:candidates里有重复元素,但是最后的集合不能重复
将candidates进行排序(sort)后循环时判决 i>index && candidates[i] == candidates[i - 1]
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& candidates, int target, int sum, int index) {
if (sum > target)
return;
if (sum == target) {
result.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]);
sum += candidates[i];
backtracking(candidates, target, sum, i + 1);
sum -= candidates[i];
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
result.clear();
path.clear();
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0, 0);
return result;
}
};
131.分割回文串
难点:
- 判断回文串(isPalindrome—双指针法)
- 分割和回溯的关系
class Solution {
private:
vector<vector<string>> result;
vector<string> path;
void backtracking(string s, int index) {
if (index >= s.size()) {
result.push_back(path);
return;
}
for (int i = index; i < s.size(); i++) {
if (isPalindrome(s, index, i)) {
string str = s.substr(index, i - index + 1);
path.push_back(str);
} else {
continue;
}
backtracking(s, i + 1);
path.pop_back();
}
}
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;
}
public:
vector<vector<string>> partition(string s) {
result.clear();
path.clear();
backtracking(s, 0);
return result;
}
};