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.
Note: 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] ]
class Solution {
public:
//int threeSumClosest(vector<int>& nums, int target)
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int>> foursum;
vector<int> sum;
if (nums.empty()) return foursum;
int mini = nums[0] + nums[1] + nums[2] + nums[3];
for (int i = 0; i < nums.size()-3; i++) {
if (i != 0 && nums[i] > target&& nums[i]>0) break;
if (i != 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < nums.size()-2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
if (nums[i] + nums[j] > target&&nums[j]>0) break;
int left = j + 1, right = nums.size() - 1;
int sums = nums[i] + nums[j];
while (left < right) {
if (sums + nums[left] + nums[right] == target) {
sum.push_back(nums[i]);
sum.push_back(nums[j]);
sum.push_back(nums[left]);
sum.push_back(nums[right]);
foursum.push_back(sum);
sum.clear();
while (nums[left + 1] == nums[left]) left++;
left++;
}
else if (sums + nums[left] + nums[right] < target) {
left++;
}
else {
right--;
}
}
}
}
return foursum;
}
};