Description
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]
]
Solution
- 排序夾逼法
和15. 3Sum類似蒙具,只不過多加了一層循環(huán)而已版确,要保證結(jié)果不重復(fù)
vector<vector<int> > fourSum(vector<int> &nums, int target) {
vector<vector<int> > ret;
if (nums.size() < 4) {
return ret;
}
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 3; ++i) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.size() - 2; ++j) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int s = j + 1, t = nums.size() - 1, curTarget = target -(nums[i] + nums[j]);
while (s < t) {
//cout<<nums[s]<<nums[t]<<target<<endl;
if (nums[s] + nums[t] < curTarget) {
s++;
} else if (nums[s] + nums[t] > curTarget) {
t--;
} else {
ret.push_back({nums[i], nums[j], nums[s], nums[t]});
while (s < t && nums[s] == nums[s + 1]) {
s++;
}
while (t > s && nums[t] == nums[t - 1]) {
t--;
}
s++;
t--;
}
}
}
}
return ret;
}