39. 组合总和
![](https://i-blog.csdnimg.cn/blog_migrate/747f5aa2ed1e6bc8aa7b22ef907e5964.png)
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtracking(int target,int sum,vector<int>& candidates,int startindex){
if(sum==target) result.push_back(path);
if(sum>target) return;
for(int i=startindex;i<candidates.size();i++){
sum+=candidates[i];
path.push_back(candidates[i]);
backtracking(target,sum,candidates,i);
path.pop_back();
sum-=candidates[i];
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
int sum=0;
backtracking(target,sum,candidates,0);
return result;
}
};
40.组合总和II
![](https://i-blog.csdnimg.cn/blog_migrate/32c3e7bf19d6c5c64126740d6a819d03.png)
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& candidates,int target,int sum,int startindex,vector<bool>& uesd){
if(sum==target) {
result.push_back(path);
return;
}
if(sum>target) return;
for(int i=startindex;i<candidates.size()&&sum+candidates[i]<=target;i++){
if(i>0&&candidates[i]==candidates[i-1]&&uesd[i-1]==false){
continue;
}
sum+=candidates[i];
path.push_back(candidates[i]);
uesd[i]=true;
backtracking(candidates,target,sum,i+1,uesd);
uesd[i]=false;
sum-=candidates[i];
path.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<bool> uesd(candidates.size(),false);
path.clear();
result.clear();
sort(candidates.begin(),candidates.end());
backtracking(candidates,target,0,0,uesd);
return result;
}
};
131.分割回文串
class Solution {
public:
vector<vector<string>> result;
vector<string> path;
void backtracking(int startindex,string& s){
if(startindex>=s.size()){
result.push_back(path);
return;
}
for(int i=startindex;i<s.size();i++){
if(isdrone(s,startindex,i)){
string str = s.substr(startindex,i-startindex+1);
path.push_back(str);
}else{
continue;
}
backtracking(i+1,s);
path.pop_back();
}
}
bool isdrone(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;
}
vector<vector<string>> partition(string s) {
backtracking(0,s);
return result;
}
};