题目:
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: 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] ]
思路:
可以开始总结mSum问题了:在空间复杂度为O(1)的前提下,除了2sum需要用O(nlogn)的时间复杂度之外,mSum问题的时间复杂度一般为O(n^(m-1))。这是因为,在排好序的情况下,对前m-2个元素需要进行枚举,而最后2个元素用双指针进行一次扫描即可。注意根据题目要求,每个被枚举的元素都要考虑去重。
代码:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target)
{
vector<vector<int>> result;
if(nums.size() < 4) return result;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size() - 3; i++)
{
for(int j = i+1; j < nums.size() - 2; j++)
{
int left = j + 1, right = nums.size() - 1;
while(left < right)
{
int val = nums[i] + nums[j] + nums[left] + nums[right];
if(val < target)
{
++left;
}
else if(val > target)
{
--right;
}
else
{
vector<int> vec{ nums[i], nums[j], nums[left], nums[right]};
result.push_back(vec);
while(left < right && nums[left] == nums[left + 1])
left++;
while(left < right && nums[right] == nums[right - 1])
right--;
left++, right--;
}
}
while(nums[j] == nums[j+1]) j++;
}
while(nums[i] == nums[i+1]) i++;
}
return result;
}
};