Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
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] ]
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
if(nums.size() < 4) return res;
std::sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size()-3; ++i){
int target2 = target - nums[i]; // 3 sum
for(int j = i+1; j < nums.size()-2; ++j){
int target3 = target2 - nums[j];
int begin = j+1, end = nums.size()-1;
while(begin < end){
if(nums[begin] + nums[end] < target3)
begin++;
else if(nums[begin] +nums[end] > target3)
end--;
else{
vector<int> temp(4,0);
temp[0] = nums[i];
temp[1] = nums[j];
temp[2] = nums[begin];
temp[3] = nums[end];
res.push_back(temp);
while(begin < end && nums[begin] == temp[2]) ++begin;
while(begin < end && nums[end] == temp[3]) --end;
}
}
while(j+1 < nums.size()-2 && nums[j+1] == nums[j]) ++j;
}
while(i+1 < nums.size()-3 && nums[i+1] ==nums[i]) ++i;
}
return res;
}
};