和之前的一样的思路 O(N^(k-1))
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int length = nums.size();
vector<vector<int>> ans;
vector<int> res;
for(int i=0;i<length;i++)
{
if(i==0||nums[i]!=nums[i-1]){
for(int j=i+1;j<length;j++)
{
if(j==i+1||nums[j]!=nums[j-1])
{
int start = j+1;
int end = length-1;
while(start<end)
{
res.clear();
if(nums[i]+nums[j]+nums[start]+nums[end]<target)
{
start++;
continue;
}
if(nums[i]+nums[j]+nums[start]+nums[end]>target)
{
end--;
continue;
}
if(nums[i]+nums[j]+nums[start]+nums[end]==target)
{
res.push_back(nums[i]);
res.push_back(nums[j]);
res.push_back(nums[start]);
res.push_back(nums[end]);
ans.push_back(res);
while(start<end&&nums[end]==nums[end-1])
end--;
while(start<end&&nums[start]==nums[start+1])
start++;
start++;
end--;
}
}
}
}
}
}
return ans;
}
};