class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num,int target) {
int n = num.size();
sort(num.begin(), num.end());
vector<vector<int> > res;
if(n<4) return res;
for(int i = 0; i < n-2; i++)
for(int j=i+1;j<n-1;j++)
{
int target2 = target - num[i]-num[j];
twoSum(num,i, j+1, target2, res);
}
sort(res.begin(),res.end());
res.erase(unique(res.begin(),res.end()),res.end());
return res;
}
void twoSum(vector<int> &sortedNum, int i,int start, int target, vector<vector<int> >&res)
{
int head = start, tail = sortedNum.size() - 1;
while(head < tail)
{
int tmp = sortedNum[head] + sortedNum[tail];
if(tmp < target)
head++;
else if(tmp > target)
tail--;
else
{
res.push_back(vector<int>{sortedNum[i],sortedNum[start-1], sortedNum[head], sortedNum[tail]});
head++;
tail--;
}
}
}
};