Given an array S of n integers, are there elements a,
b, c, 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,
    abcd)
  • 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)

点击打开原题链接

N SUM和都是一个德性,代码例如以下:

class Solution
{
private:
vector<vector<int> > ret;
public:
vector<vector<int> > fourSum(vector<int> &num, int target)
{
sort(num.begin(), num.end()); ret.clear(); for(int i = 0; i < num.size(); i++)
{
if (i > 0 && num[i] == num[i-1])
continue; for(int j = i + 1; j < num.size(); j++)
{
if (j > i + 1 && num[j] == num[j-1])
continue; int k = j + 1;
int t = num.size() - 1; while(k < t)
{
if (k > j + 1 && num[k] == num[k-1])
{
k++;
continue;
} if (t < num.size() - 1 && num[t] == num[t+1])
{
t--;
continue;
} int sum = num[i] + num[j] + num[k] + num[t]; if (sum == target)
{
vector<int> a;
a.push_back(num[i]);
a.push_back(num[j]);
a.push_back(num[k]);
a.push_back(num[t]);
ret.push_back(a);
k++;
t--;
}
else if (sum < target)
k++;
else
t--;
}
}
} return ret;
}
};

4Sum_leetCode的更多相关文章

  1. 详谈Format String(格式化字符串)漏洞

    格式化字符串漏洞由于目前编译器的默认禁止敏感格式控制符,而且容易通过代码审计中发现,所以此类漏洞极少出现,一直没有笔者本人的引起重视.最近捣鼓pwn题,遇上了不少,决定好好总结了一下. 格式化字符串漏 ...

随机推荐

  1. Beginning iOS 8 Programming with Swift-TableView

    UITableView控件使用 使用UITableView,在控件库中,拖拽一个Table View到ViewController中,在Controller的后台代码中需要继承UITableViewD ...

  2. tld自定义标签系列--使用body-content的作用--比较有用

    body-content的值有下面4种: <xsd:enumeration value="tagdependent"/> <xsd:enumeration val ...

  3. DoTween 部分中文文档

    前言 DOTween现在还处于 alpha,所以还有一些缺失的功能(如路径插件,附加回调和其它的tween选项),这个文档在不久的将来可能会改变. 一.术语 Tweener 一个tween控制valu ...

  4. Vue.js常用指令汇总(v-if//v-show//v-else//v-for//v-bind//v-on等)

    有时候指令太多会造成记错.记混的问题,所以本文在记忆的时候会采用穿插记忆的方式,交叉比对,不易出错. 本文主要讲了一下六个指令: v-if//v-show//v-else//v-for//v-bind ...

  5. flask的session解读及flask_login登录过程研究

    #!/usr/bin/env python # -*- coding: utf-8 -*- from itsdangerous import URLSafeTimedSerializer from f ...

  6. JAVA之继承的必要性

    //说明继承的必要性package com.test; public class test { /**     * @param args     */    public static void m ...

  7. java 文件上传数据库

    存储文件的数据库类型: 1.oracle :Blob,bfile类型 2.mysql:longblob类型 3.sqlserver :varbinary(Max)类型 文件都是以二进制流存入数据库的, ...

  8. Filter及FilterChain的详解

    一.Filter的介绍及使用 什么是过滤器? 与Servlet相似,过滤器是一些web应用程序组件,可以绑定到一个web应用程序中.但是与其他web应用程序组件不同的是,过滤器是"链&quo ...

  9. spring boot 使用mybatis-generator

    mybatis-generator官网: http://www.mybatis.org/generator/running/runningWithMaven.html 在pom.xml中的 build ...

  10. ElasticSearch中设置排序Java

    有用的链接:http://stackoverflow.com/questions/12215380/sorting-on-several-fields-in-elasticsearch 有的时候,需要 ...