# leecode_18 4Sum (k Sum)

98人阅读 评论(0)

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

• Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
• The solution set must not contain duplicate quadruplets.

For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

A solution set is:
(-1,  0, 0, 1)
(-2, -1, 1, 2)
(-2,  0, 0, 2)

( {0}, 2 )    ( { 0,0 }, 2)  ( {0,0,0}, 2 )

#include <iostream>
#include <string>
#include <unordered_map>
#include <queue>
#include <unordered_set>
using namespace std;

vector<vector<int>> fourSum(vector<int>& nums, int target) {
int k=4;
vector<vector<int>> res;
queue< pair< vector<int>,int > > que;
sort(nums.begin(),nums.end());
//ini
for (int i=0;i<nums.size();i++){
int low_bound=lower_bound(nums.begin(), nums.end(),nums[i])-nums.begin();
int up_bound=upper_bound(nums.begin(),nums.end(),nums[i])-nums.begin();
vector<int> temp;
for (int i=low_bound;i<up_bound;i++){
temp.push_back(nums[i]);
que.push(make_pair(temp,up_bound-1));
}
i=up_bound-1;
}

while(!que.empty()){
vector<int> vec=que.front().first;
int index=que.front().second;
que.pop();
//cout<<endl;
int sum=0;
for (int i=0;i<vec.size();i++)
sum+=vec[i];
if (vec.size()==k && sum==target){
res.push_back(vec);
continue;
}

if (vec.size()==k-1 && index<=nums.size()-2)
for (int i=index+1;i<nums.size();i++){
if (sum+nums[i]==target){
vec.push_back(nums[i]);
res.push_back(vec);
break;
}
continue;
}

if (vec.size()<k-1 && index<=nums.size()-2){
int temp=sum;
vector<int> v_temp=vec;
for (int i=index+1;i<nums.size();i++){
int p=nums[i];
int low_bound=lower_bound(nums.begin(), nums.end(),p)-nums.begin();
int up_bound=upper_bound(nums.begin(),nums.end(),p)-nums.begin();

for (int i=low_bound;i<up_bound;i++){
sum+=nums[i];
vec.push_back(nums[i]);
if (vec.size()<=k){
//                        for (int j=0;j<vec.size();j++)
//                            cout<<vec[j]<<" ";
//                        cout<<endl;
que.push(make_pair(vec,up_bound-1));
}

}
vec=v_temp;
sum=temp;
i=up_bound-1;
}
}

}

return res;
}

int main(){
vector<int> vec1={1,0, -1, 0, -2, 2};

vector<vector<int>> res=fourSum(vec1,0);

for (int i=0;i<res.size();i++){
for(int j=0;j<res[i].size();j++)
cout<<res[i][j]<<" ";
cout<<endl;
}

return 0;

}

1
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：25971次
• 积分：1732
• 等级：
• 排名：千里之外
• 原创：152篇
• 转载：9篇
• 译文：0篇
• 评论：13条
最新评论