LeetCode 39. 组合总和
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
int count=0;
void backtracking(vector<int>& candidates,int target,int index){
if(count==target){
result.push_back(path);
return ;
}
if(count>target)return ;
for(int i=index;i<candidates.size();i++){
path.push_back(candidates[i]);
count+=candidates[i];
backtracking(candidates,target,i);
path.pop_back();
count-=candidates[i];
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
backtracking(candidates,target,0);
return result;
}
};
注意在for中,传递的都是i,不是index,不要写成index了
在实现backtracking递归时,需要直接传递i,而不是i+1,因为元素可以不断重复。
LeetCode 40.组合总和II
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
int count=0;
void backtracking(vector<int>& candidates,int target,int index,vector<bool>& used){
if(count>target)return ;
if(count==target){
result.push_back(path);
return ;
}
for(int i=index;i<candidates.size();i++){
if(i>0 && candidates[i]==candidates[i-1] && used[i-1]==false){
continue;
}
path.push_back(candidates[i]);
count+=candidates[i];
used[i]=true;
backtracking(candidates,target,i+1,used);
used[i]=false;
count-=candidates[i];
path.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<bool> used(candidates.size(),false);
sort(candidates.begin(),candidates.end());
backtracking(candidates,target,0,used);
return result;
}
};
used也同样参与回溯,这个看卡哥视频更好理解,直接看题解我没看懂。
关于candidates[i]==candidates[i-1] && used[i-1]==false
作为判断条件,这个要多看几遍理解
LeetCode 131.分割回文串
class Solution {
public:
vector<string> path;
vector<vector<string>> result;
bool isPalindrome(const 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 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();
}
}
vector<vector<string>> partition(string s) {
backtracking(s,0);
return result;
}
};