class Solution {
public:
vector
<vector
<int>> fourSum(vector
<int>& nums
, int target
) {
int n
= nums
.size();
vector
<vector
<int>> ans
;
if (n
< 4)
{
return ans
;
}
sort(nums
.begin(), nums
.end());
for (int first
= 0; first
< n
- 3; first
++)
{
if (first
> 0 && nums
[first
] == nums
[first
- 1])
{
continue;
}
for (int second
= first
+ 1; second
< n
- 2; second
++)
{
if (second
> first
+ 1 && nums
[second
] == nums
[second
- 1])
{
continue;
}
int third
= second
+ 1, fourth
= n
- 1;
while (third
< fourth
)
{
if (third
> second
+ 1 and nums
[third
] == nums
[third
- 1])
{
third
++;
continue;
}
if (fourth
< n
- 1 && nums
[fourth
] == nums
[fourth
+ 1])
{
fourth
--;
continue;
}
if (nums
[first
] + nums
[second
] + nums
[third
] + nums
[fourth
] == target
)
{
ans
.push_back({ nums
[first
], nums
[second
], nums
[third
], nums
[fourth
] });
third
++;
fourth
--;
}
else if (nums
[first
] + nums
[second
] + nums
[third
] + nums
[fourth
] > target
)
{
fourth
--;
}
else
{
third
++;
}
}
}
}
return ans
;
}
};
转载请注明原文地址: https://lol.8miu.com/read-34145.html