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)
class Solution {public: vector> fourSum(vector &num, int target) { vector > res; if(num.size()<4)return res; sort(num.begin(),num.end()); int c,d; for(int a=0;a 0&&num[a]==num[a-1]) continue; for(int b=a+1;b a+1&&num[b]==num[b-1]) continue; c=b+1; d=num.size()-1; while(c b+1&&num[c]==num[c-1]) { c++; continue; } if(d target)d--; else { vector temp; temp.push_back(num[a]); temp.push_back(num[b]); temp.push_back(num[c]); temp.push_back(num[d]); res.push_back(temp); c++; d--; } } } } return res; }};