这几天有点偷懒了,所以写的少了。今天以后每天都会写
39. 组合总和
class Solution {
public:
vector<int> path;
vector<vector<int>> ans;
int sum = 0;
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
//如果要用这种简化的方法,这里一定记得要排序,因为如果不排序,就会损失一些数组
//比如【3,2,4】,如果3不满足,2满足,不排序将不会遍历2了
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0, sum);
return ans;
}
void backtracking(vector<int>& candidates, int target, int startindex, int& sum){
// if(sum > target) return;
if(sum == target){
ans.push_back(path);
return;
}
for(int i = startindex; i < candidates.size() && sum+candidates[i] <= target; i++){
sum+=candidates[i];
path.push_back(candidates[i]);
backtracking(candidates, target, i, sum);
path.pop_back();
sum-=candidates[i];
}
}
};
40. 组合总和 II
class Solution {
public:
vector<int> path;
vector<vector<int>> ans;
int sum = 0;
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<bool> used(candidates.size(), false);
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0, sum, used);
return ans;
}
void backtracking(vector<int>& candidates, int target, int startindex, int sum, vector<bool>& used){
//切记每个数字只能用一次但是数组里会出现重复数字
if(sum > target) return;
if(sum == target){
ans.push_back(path);
return;
}
for(int i = startindex; i < candidates.size();i++){
//把回溯问题抽象为树枝和数层的关系,因为集合里含有重复元素,所以同一数枝使用并没有
//关系,但是如果同一数层再选择重复元素就会出事了
if(i>0 && candidates[i] == candidates[i-1] && used[i-1] == false) continue;
sum+=candidates[i];
used[i] = true;
path.push_back(candidates[i]);
backtracking(candidates, target, i+1, sum, used);
sum-=candidates[i];
used[i] = false;
path.pop_back();
}
}
};
具体的解题方法可以参照代码随想录,我觉得非常好,嘿嘿
代码随想录
下面的方法介绍不同used数组来解决
class Solution {
public:
vector<int> path;
vector<vector<int>> ans;
int sum = 0;
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, sum, 0);
return ans;
}
void backtracking(vector<int>& candidates, int target, int sum, int startindex){
if(sum > target) return;
if(sum == target){
ans.push_back(path);
return;
}
for(int i = startindex; i < candidates.size(); i++){
//对同一数层使用过的元素进行跳过
if(i > startindex && candidates[i] == candidates[i-1] && i!=0) continue;
path.push_back(candidates[i]);
sum+=candidates[i];
backtracking(candidates, target, sum, i+1);
path.pop_back();
sum-=candidates[i];
}
}
};