Week10: 4Sum
Difficulty:Medium
1.Problem
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]
]
2.Algorithm
1.首先将input数组进行排序,记max为input数组最大值,min为input数组最小值,
若4*max小于target或者4*min大于target,则立刻返回空数组2.若1中两个条件都不符合,则从数组开头遍历整个数组,在每一次循环调用Leecode week7中的3Sum函数;同时在每一次循环中去掉一些重复数字。
3.Solution
class Solution {
public:
vector<vector<int> > fourSum(vector<int>& nums, int target) {
int size = nums.size();
vector<vector<int> > ans;
sort(nums.begin(),nums.begin()+size);
if(size < 4) return ans;
int max = nums[size-1];
if(4 * max < target || 4 * nums[0] > target) return ans;
for(int i = 0; i < size - 1; i++) {
if(i > 0 && nums[i] == nums[i-1]) continue;
int z = nums[i];
if(z + 3 * max < target) continue;
if(4 * z > target) break;
if(4 * z == target && i + 3 < size - 1 && nums[i+3] == z) {
vector<int> temp;
temp.push_back(z);
temp.push_back(z);
temp.push_back(z);
temp.push_back(z);
ans.push_back(temp);
break;
}
vector<vector<int> > temp = threeSum(nums, target - z, i + 1, size - 1, z);
ans.insert(ans.end(), temp.begin(), temp.end());
}
return ans;
}
vector<vector<int> > threeSum(vector<int>& nums, int target, int start, int end, int origin) {
vector<vector<int> > ans;
for(int i = start; i < end; i++) {
if(i > start && nums[i] == nums[i-1]) {
continue;
}
int k = i + 1, n = end;
while(k < n) {
int sum = nums[i]+nums[k]+nums[n];
if(sum == target) {
vector<int> temp;
temp.push_back(origin);
temp.push_back(nums[i]);
temp.push_back(nums[k]);
temp.push_back(nums[n]);
ans.push_back(temp);
while(k < n && nums[k] == nums[k+1]) k++;
while(k < n && nums[n] == nums[n-1]) n--;
k++;
n--;
}
else if(sum < target) k++;
else n--;
}
}
return ans;
}
};