給定一個有n個數字的數組S,在S中是否存在元素a,b,c和d的和恰好滿足a + b + c + d = target。
找出數組中所有的不想等的這四個元素,其和等於target。
備注:
在(a,b,c,d)中的元素必須從小到大排列。(a ≤ b ≤ c ≤ d)
其結果必須不能夠重復。
例如,給定S = {1 0 -1 0 -2 2},target = 0。
一個結果集為:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
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.
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)
具體的方法和前面兩道題一樣,我就不再贅述了。
class Solution {
public:
vector> fourSum(vector& nums,int target) {
sort(nums.begin(), nums.end());
vector> result;
int len = nums.size();
for (int current = 0; current < len - 3;current++)
{
for(int second = current+1;second target)
back--;
else
{
vector v(4);
v[0]=nums[current];
v[1]=nums[second];
v[2]=nums[front];
v[3]=nums[back];
result.push_back(v);
do {
front++;
} while (front < back&&nums[front - 1] == nums[front]);
do {
back--;
} while (front < back&&nums[back + 1] == nums[back]);
}
}
while(second < len-2&&nums[second+1]==nums[second])
second++;
}
while (current < len - 3 && nums[current + 1] == nums[current])
current++;
}
return result;
}
};
和本道題關聯密切的題目推薦:
傳送門:LeetCode 15 3Sum(3個數的和)
傳送門:LeetCode 16 3Sum Closest(最接近的3個數的和)