4Sum

Given an array S of n integers, are there elements abc, 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:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • 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类似,只是我们现在需要遍历两个元素,a,b,然后在利用两个指针的方法求c,d
 
 class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) { int n=num.size();
int i,j,k,l;
int a,b,c,d;
sort(num.begin(),num.end());
vector<vector<int> > result;
for(int i=;i<n-;i++)
{
for(int j=i+;j<n-;j++)
{
k=j+;
l=n-; while(k<l)
{
a=num[i];
if(i>&&num[i]==num[i-])
{
break;
} b=num[j];
if(j>i+&&num[j]==num[j-])
{
break;
} c=num[k];
if(k>j+&&num[k]==num[k-])
{
k++;
continue;
} d=num[l];
if(l<n-&&num[l]==num[l+])
{
l--;
continue;
} int sum=a+b+c+d; if(sum<target)
{
k++;
}
else if(sum>target)
{
l--;
}
else
{
vector<int> tmp();
tmp[]=a;
tmp[]=b;
tmp[]=c;
tmp[]=d;
result.push_back(tmp);
k++;
l--;
}
}
}
}
return result;
}
};

最新文章

  1. RABBITMQ(小总结 持续更新...
  2. Oracle 常见问题
  3. Redis的过滤器(SCAN)功能
  4. 【转】android布局属性详解
  5. FS,FT,DFS,DTFT,DFT,FFT的联系和区别
  6. jps用法
  7. Dev-C++之开启装逼效果
  8. package.json 的语法解释
  9. linux下如何使用USB存储设备
  10. OpenCV探索之路(二十四)图像拼接和图像融合技术
  11. BZOJ-3040-最短路(road)
  12. C语言-学生博客汇总
  13. Java开发笔记(十九)规律变化的for循环
  14. Tornado-Ajax
  15. Android目录结构及作用
  16. day 12 内置函数,装饰器,递归函数
  17. ibatis的缓存机制
  18. 前端代码在线调试&amp;分享网站
  19. iOS 开发学习-import和include的区别
  20. 006 ajax验证用户名

热门文章

  1. base-css
  2. Eclipse-maven项目发布到tomcat没有附带lib拷贝
  3. 【POJ 3320】Jessica&#39;s Reading Problemc(尺取法)
  4. 【ZOJ 3502】Contest
  5. 人工蜂群算法-python实现
  6. BZOJ2654 tree
  7. POJ 1740 A New Stone Game
  8. p2p软件如何穿透内网进行通信
  9. POJ2387 Til the Cows Come Home(SPFA + dijkstra + BallemFord 模板)
  10. DALSA Coreco - 图像处理软件(Sapera LT )