39.组合总和
class Solution {
private:
vector<int> combine;
vector<vector<int>> result;
int count = 0;
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
backtracking(candidates, target, 0);
return result;
}
void backtracking(vector<int>& candidates, int target, int startIndex) {
// 终止条件 如果count已经大于target,那么就不能继续累加了,立即返回,并执行回溯
if(count > target) return;
// 回收结果
if(count == target) {
result.push_back(combine);
return ;
}
for(int i = startIndex; i < candidates.size(); ++i) {
combine.push_back(candidates[i]);
count += candidates[i];
// startIndex = i表示可以重复选取元素,i + 1表示不重复选取
backtracking(candidates, target, i);
count -= candidates[i];
combine.pop_back();
}
}
};
40.组合总和II
- 树枝去重:再for循环中去重,集合间去重对应的是树层去重
- 树层去重:再递归中去重,集合中去重对应的是树层去重
本题集合中允许重复元素,集合间不允许重复,所以是树枝去重,去重逻辑应写在for循环中
class Solution {
private:
vector<int> combine;
vector<vector<int>> result;
int sum;
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0);
return result;
}
void backtracking(vector<int>& candidates, int target, int startIndex) {
// 终止条件
if(sum > target) return ;
// 收集结果
if(sum == target) {
result.push_back(combine);
return ;
}
for(int i = startIndex; i < candidates.size(); ++i) {
// 树枝间去重,在每一次选树枝的时候保证和前一个树枝不同
if(i > startIndex && candidates[i] == candidates[i - 1]) continue;
combine.push_back(candidates[i]);
sum += candidates[i];
backtracking(candidates, target, i + 1);
sum -= candidates[i];
combine.pop_back();
}
}
};
131.分割回文串
class Solution {
private:
vector<string> split;
vector<vector<string>> result;
public:
vector<vector<string>> partition(string s) {
backtracking(s, 0);
return result;
}
bool isPalindromic(string s) {
int left = 0, right = s.size() - 1;
while(left < right) if(s[left++] != s[right--]) return false;
return true;
}
void backtracking(string& s, int startIndex) {
// 终止条件
if(startIndex == s.size()) {
result.push_back(split);
return ;
}
for(int i = startIndex; i < s.size(); ++i) {
// 判断是否是回文串
string str = s.substr(startIndex, i - startIndex + 1);
if(isPalindromic(str))
split.push_back(str);
else continue;
backtracking(s, i + 1);
split.pop_back();
}
}
};
标签:39,return,target,int,随想录,第二十七,startIndex,vector,candidates
From: https://www.cnblogs.com/cscpp/p/18231949