forked from moranzcw/LeetCode-NOTES
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.cpp
49 lines (45 loc) · 1.7 KB
/
solution.cpp
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
class Solution
{
public:
vector<vector<int>> fourSum(vector<int>& nums, int target)
{
vector<vector<int> > result;
if(nums.size() == 0)
return result;
sort(nums.begin(),nums.end());
for( int pos1 = 0;pos1<nums.size();pos1++)
{
for(int pos2 = pos1 + 1;pos2<nums.size();pos2++)
{
for(int pos3 = pos2 + 1, pos4 = nums.size() - 1; pos3 < pos4;)
{
int sum = nums[pos1] + nums[pos2] + nums[pos3] + nums[pos4];
if(sum == target)
{
vector<int> tempResult;
tempResult.push_back(nums[pos1]);
tempResult.push_back(nums[pos2]);
tempResult.push_back(nums[pos3]);
tempResult.push_back(nums[pos4]);
result.push_back(tempResult);
while( pos3+1 < pos4 && nums[pos3+1] == nums[pos3])
pos3++;
pos3++;
while( pos4-1 > pos3 && nums[pos4-1] == nums[pos4])
pos4--;
pos4--;
}
else if(sum < target)
pos3++;
else
pos4--;
}
while( pos2+1 < nums.size() && nums[pos2+1] == nums[pos2])
pos2++;
}
while( pos1+1 < nums.size() && nums[pos1+1] == nums[pos1])
pos1++;
}
return result;
}
};