Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.
Example:
Given array nums = [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] ]
给定一个含n个整数的数组nums和一个整数target,判断nums中是否存在是个整数a、b、c、d,它们满足a+b+c+d=target?若存在,找出所有符合条件的整数对。
分析:此题与3Sum没什么区别,只需要在此基础上多加一层for循环即可,代码如下:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> rst;
sort(nums.begin(), nums.end());
int cnt = nums.size();
int left = 0, right = 0;
int diff = 0, diff1 = 0, tmp = 0;
for (int i = 0; i < cnt - 3; i++)
{
if (i > 0 && nums[i] == nums[i - 1])
continue;
diff = target - nums[i];
for (int j = i + 1; j < cnt - 2; j++)
{
if (j > i+1 && nums[j] == nums[j - 1])
continue;
diff1 = diff - nums[j];
left = j + 1;
right = cnt - 1;
while (left < right)
{
tmp = nums[left] + nums[right];
if (tmp == diff1)
{
rst.push_back({ nums[i],nums[j],nums[left],nums[right] });
while (left < right)
{
if (nums[left] == nums[left + 1])
left++;
else
break;
}
while (left < right)
{
if (nums[right] == nums[right - 1])
right--;
else
break;
}
left++;
right--;
}
else if (tmp < diff1)
left++;
else
right--;
}
}
}
return rst;
}
浙公网安备 33010602011771号