LeetCode刷題之回溯演算法組合總和問題
阿新 • • 發佈:2022-04-05
求解在一個數組中,找出所有滿足數字和為目標數的組合
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