39.组合总和
代码如下
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& candidates, int target, int sum, int startIndex) {
if (sum == target) {
result.push_back(path);
return;
}
// 如果 sum + candidates[i] > target 就终止遍历
for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; 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();
sort(candidates.begin(), candidates.end()); // 需要排序
backtracking(candidates, target, 0, 0);
return result;
}
};
40.组合总和II
得有去重,并且可以使用两个相同的数字,可以定义一个数组看是否使用过
树层去重
树枝去重
class Solution {
private:
vector<vector<int>>result;
vector<int>path;
void backtracking(vector<int>&candidates,int target,int sum,int starIndex,vector<bool>&used){
if(sum==target){
result.push_back(path);
return ;
}
for(int i=starIndex;i<candidates.size()&&sum+candidates[i]<=target;i++){
if(i>0&&candidates[i]==candidates[i-1]&&used[i-1]==false){
continue;
}
sum+=candidates[i];
path.push_back(candidates[i]);
used[i]=true;
backtracking(candidates,target,sum,i+1,used);
used[i]=false;
sum-=candidates[i];
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<bool> used(candidates.size(),false);
path.clear();
result.clear();
sort(candidates.begin(),candidates.end());
backtracking(candidates,target,0,0,used);
return result;
}
};
131.分割回文串
class Solution {
private:
vector<vector<string>> result;
vector<string> path;
void backtracking(const string& s,int starIndex){
if(starIndex>=s.size()){
result.push_back(path);
return;
}
for(int i=starIndex;i<s.size();i++){
if(ishuiwen(s,starIndex,i)){
string str=s.substr(starIndex,i-starIndex+1);
path.push_back(str);
}else{
continue;
}
backtracking(s,i+1);
path.pop_back();
}
}
bool ishuiwen(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;
}
public:
vector<vector<string>> partition(string s) {
result.clear();
path.clear();
backtracking(s,0);
return result;
}
};