LeetCode刷题之回溯算法组合总和问题
求解在一个数组中,找出所有满足数字和为目标数的组合
1.同一个数组,组合可存在重复数字,组合也能重复
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums,int target, int sums, int startindex)
{
if(sums>target) return;
if(sums == target)
{
result.push_back(path);
return;
}
for(int i=startindex;i<nums.size()&&sums+nums[i]<=target;i++)
{
path.push_back(nums[i]);
sums+=nums[i];
backtracking(nums,target,sums,i+1);
sums-=nums[i];
path.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
result.clear();
path.clear();
sort(candidates.begin(),candidates.end());
backtracking(candidates,target,0,0);
return result;}
};
2.同一个数组,组合可存在重复数字,不能存在重复组合
//方法一
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums,int target, int sums, int startindex)
{
if(sums>target) return;
if(sums == target)
{
result.push_back(path);
return;
}
for(int i=startindex;i<nums.size()&&sums+nums[i]<=target;i++)
{
if(i-1>=startindex && nums[i]==nums[i-1])
{continue;}
path.push_back(nums[i]);
sums+=nums[i];
backtracking(nums,target,sums,i+1);
sums-=nums[i];
path.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
result.clear();
path.clear();
sort(candidates.begin(),candidates.end());
backtracking(candidates,target,0,0);
return result;}
};
//方法二
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums,int target, int sums, int startindex,vector<bool>&used)
{
if(sums>target) return;
if(sums == target)
{
result.push_back(path);
return;
}
for(int i=startindex;i<nums.size()&&sums+nums[i]<=target;i++)
{
if(i>0