欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Sum(C++) - 编程开发习题

程序员文章站 2022-03-26 19:46:59
sum(c++) - 开发习题。 given an arraynumsofnintegers and an integertarget, are there elementsa,b,c, anddi...

sum(c++) - 开发习题。

given an arraynumsofnintegers and an integertarget, are there elementsa,b,c, anddinnumssuch thata+b+c+d=target find all unique quadruplets in the array which gives the sum oftarget.

class solution {
public:
vector> foursum(vector& nums, int target)
{
vector> ret;
int n=nums.size();
if(n<4)
return ret;
sort(nums.begin(),nums.end());
for(int i=0;i<=n-4;i++)
{
for(int j=i+1;j<=n-3;j++)
{
int m=j+1;
int k=n-1;
while(m
{
if(nums[i]+nums[j]+nums[m]+nums[k]
m++;
else if(nums[i]+nums[j]+nums[m]+nums[k]>target)
k--;
else
{
ret.push_back({nums[i],nums[j],nums[m],nums[k]});
m++;
k--;
while(j
m++;
while(j
k--;
}
}
while(nums[j]==nums[j+1])
j++;
}
while(nums[i]==nums[i+1])
i++;
}
return ret;
}
};