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.
1.数组中元素个数小于4的时候;2:对数组元素进行排序;3从前到后遍历数组,注意数字相同的情况
vector<vector<int> > fourSum(vector<int> &num, int target)
{
vector<vector<int> > result;
if(num.size() <= 3)
return result;
sort(num.begin(), num.end());
vector<int> quadruplet;
int size = (int)num.size();
for(int i = 0; i < size - 3; i++)
{
if(i == 0 || num[i] != num[i-1])
{
quadruplet.push_back(num[i]);
fourSumCore(num, target - num[i], i + 1, quadruplet, result);
quadruplet.pop_back();
}
}
return result;
}
void fourSumCore(vector<int>& num, int target, int index, vector<int> &temp, vector<vector<int>> &result)
{
int size = (int)num.size();
for(int i = index; i < size - 2; i++)
{
if(i == index || num[i] != num[i-1])
{
temp.push_back(num[i]);
int leftValue = target - num[i];
int left = i + 1;
int right = size - 1;
while(left < right)
{
if(num[left] + num[right] == leftValue)
{
temp.push_back(num[left]);
temp.push_back(num[right]);
result.push_back(temp);
temp.pop_back();
temp.pop_back();
right--;
while(left < right && num[right] == num[right + 1])
right--;
}
else if(num[left] + num[right] > leftValue)
{
right--;
}
else
{
left++;
}
}
temp.pop_back();
}
}
}