Given an array
nums
of n integers and an integertarget
, are there elements a, b, c, and d innums
such that a + b + c + d =target
? Find all unique quadruplets in the array which gives the sum oftarget
.Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [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] ]
// 12/09/2020
// two pointers approach - same as 3sum - O(n^3)
vector<vector<int>> fourSum(vector<int>& nums, int target) {
if(nums.size() < 4) return {};
sort(nums.begin(), nums.end());
vector<vector<int>> result;
for(int i = 0, size = nums.size(); i < size-3; ++i){
if(i>0 && nums[i] == nums[i-1]) continue;
for(int j = i+1; j < size-2; ++j){
if(j>i+1 && nums[j] == nums[j-1]) continue;
int k = j+1, l = size-1;
while(k < l){
int s = nums[i] + nums[j] + nums[k] + nums[l];
if(s > target) l--;
else if(s < target) k++;
else {
result.push_back({nums[i], nums[j], nums[k], nums[l]});
while(k<l && nums[k] == nums[++k]);
while(k<l && nums[l] == nums[--l]);
}
}
}
}
return result;
}