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:
- 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)
Solution:
Code:
<span style="font-size:14px;">class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
const int length = num.size();
vector<vector<int> > results;
sort(num.begin(), num.end());
for (int i = 0; i < length-3; ++i) {
for (int j = i+1; j < length-2; ++j) {
int m = j+1, n = length-1;
while (m < n) {
if (num[i]+num[j]+num[m]+num[n] == target) {
vector<int> result;
result.push_back(num[i]);
result.push_back(num[j]);
result.push_back(num[m]);
result.push_back(num[n]);
results.push_back(result);
while (m+1 < n && num[m+1] == num[m]) ++m;
++m;
while (n-1 > m && num[n-1] == num[n]) --n;
--n;
} else if (num[i]+num[j]+num[m]+num[n] < target) {
while (m+1 < n && num[m+1] == num[m]) ++m;
++m;
} else {
while (n-1 > m && num[n-1] == num[n]) --n;
--n;
}
}
while (j+1 < length-2 && num[j+1] == num[j]) ++j;
}
while (i+1 < length-3 && num[i+1] == num[i]) ++i;
}
return results;
}
};</span>