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一样
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int> > res;
int n = num.size();
if( n < ) return res;
sort(num.begin(),num.end());
for(int i = ; i < n-; ++ i){
if(i != && num[i]== num[i-]) continue;
for(int j = i+; j < n-; ++ j){
if(j!=i+ && num[j] == num[j-] ) continue;
int start = j+, end = n-;
while(start < end){
int sum = num[i]+num[j]+num[start]+num[end];
if(sum > target) end--;
else if(sum < target) start++;
else{
vector<int> a;
a.push_back(num[i]);a.push_back(num[j]);
a.push_back(num[start]);a.push_back(num[end]);
res.push_back(a);
do{start++;}while(start < end && num[start] == num[start-]);
do{end--;}while(start < end && num[end] == num[end+]);
}
}
}
}
return res;
}
};

 

最新文章

  1. Does the OpenSceneGraph have a native file format?
  2. BZOJ 1179 Atm 题解
  3. 提高Java代码质量:使用枚举定义常量(转)
  4. Spring MVC 环境搭建(二)
  5. HDU 5583 Kingdom of Black and White 水题
  6. composer安装yii2或者laravel报错
  7. configure文件中判断某函数或库是否存在的一个方法
  8. 理解screenX clientX pageX概念
  9. hibernate多对一的操作解析
  10. oracle表空间创建及管理
  11. 探索Oracle之数据库升级七 11gR2 to 12c 升级完毕后插入PDB
  12. jquery 如何动态添加、删除class样式方法介绍_jquery_脚本之家
  13. java面试题(一)
  14. 异步请求之ajax
  15. python待学习内容
  16. 在anguler项目中引用fullCalendar
  17. 动手动脑(lesson 8)
  18. jira7.3.6添加导出excel的按钮
  19. sgu
  20. JBoss 系列四十九:JBoss 7/WildFly 中端口使用列表

热门文章

  1. ArcGIS Server开发教程系列(2)配置ARCMAP和ARCCatalog发布服务
  2. 使用ASP.NET WEB API构建基于REST风格的服务实战系列教程(一)——使用EF6构建数据库及模型
  3. sobel算子的一些细节
  4. Hive 字符串操作[转]
  5. postgresql是如何处理死连接(转)
  6. codevs1183 泥泞的道路
  7. Java中的BoneCP数据库连接池用法
  8. Android 一些基本组件的使用
  9. ASP.NET基础代码备忘
  10. PHPStorm XDebug的安装