Leetcode 4Sum

时间:2022-11-02 09:38:22

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)
与3sum一样
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int> > res;
int n = num.size();
if( n < ) return res;
sort(num.begin(),num.end());
for(int i = ; i < n-; ++ i){
if(i != && num[i]== num[i-]) continue;
for(int j = i+; j < n-; ++ j){
if(j!=i+ && num[j] == num[j-] ) continue;
int start = j+, end = n-;
while(start < end){
int sum = num[i]+num[j]+num[start]+num[end];
if(sum > target) end--;
else if(sum < target) start++;
else{
vector<int> a;
a.push_back(num[i]);a.push_back(num[j]);
a.push_back(num[start]);a.push_back(num[end]);
res.push_back(a);
do{start++;}while(start < end && num[start] == num[start-]);
do{end--;}while(start < end && num[end] == num[end+]);
}
}
}
}
return res;
}
};