coding
unsky
deepdim
thought

4Sum

id18. 4Sum Add to List QuestionEditorial Solution My Submissions
Total Accepted: 101633
Total Submissions: 394751
Difficulty: Medium
Contributors: Admin
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]
]

和3sum差不多 关键是处理重复

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
if(nums.size()<4)
return res;
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 k=j+1;
int m=nums.size()-1;
while(k<m)
{
if(nums[i]+nums[j]+nums[k]+nums[m]==target)
{
vector<int> vec;
vec.push_back(nums[i]);
vec.push_back(nums[j]);
vec.push_back(nums[k]);
vec.push_back(nums[m]);
res.push_back(vec);
m--;
k++;
while(nums[k]==nums[k-1]&&k<nums.size()-1)
{k++;}
while(nums[m]==nums[m+1]&&m>0)
{m--;}
}
else if(nums[k]+nums[m]<target-nums[i]-nums[j])
{k++;
while(nums[k]==nums[k-1]&&k<nums.size()-1)
{k++;}
}
else if(nums[k]+nums[m]>target-nums[i]-nums[j])
{m--;
while(nums[m]==nums[m+1]&&m>0)
{m--;}
}
}
while(nums[j+1]==nums[j]&&j+1<nums.size()-1)
{
j++;
}
}
while(nums[i+1]==nums[i]&&i+1<nums.size()-1)
{
i++;
}
}
return res;
}
};

坚持原创技术分享,您的支持将鼓励我继续创作!