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. 你也许还不知道const_cast,static_cast,dynamic_cast,reinterpret_cast的区别吧?

    [QQ群: 189191838,对算法和C++感兴趣可以进来]       开篇立意: C++中各种转换令人眼花缭乱,看似差不多,实际差很多,而且在当今时间,做一个"差不多先生"其 ...

  2. SQL SERVER 内存学习系列

    http://www.cnblogs.com/double-K/p/5049417.html http://blog.sina.com.cn/s/blog_5deb2f5301014wti.html ...

  3. .net / java /安卓des加密互通

    一 . C#.net /// <summary> /// 加密数据 /// </summary> /// <param name="Text"> ...

  4. RMAN BACKUP

    转自 RMAN BACKUP backup terminology Using the RMAN BACKUP Command to Create Backups Server-Managed Con ...

  5. 模拟Spring中的getBean方法

    一直知道Spring是运用反射技术的,但具体怎么用呢?今天就模拟下getBean方法. 步骤: 1.用Dom4j解析xml配置文件,取出我们需要的信息 2.遍历Bean节点,根据每个Bean节点的cl ...

  6. Android自定义View(二)

    前言 魅族手机的闹钟应用中有个倒计时,这个控件还是蛮有趣的.左边是魅族闹钟,右边是我们最终实现的效果,虽然有些细节还需优化,不过基本上已经达到了想要的效果,我们先来就来看看如何实现吧. 分析 确定宽高 ...

  7. 为什么代理属性设置成assign为了防止生成保留环来

    循环引用 全部的引用计数系统, 都存在循环应用的问题, 比如以下的引用关系: 1. 对象a创建并引用到了对象b 2. 对象b创建并引用到了对象c 3. 对象c创建并引用到了对象b 这时候b和c的引用计 ...

  8. 信号驱动IO

    [1]信号驱动IO 应用程序:1)应用程序要捕捉SIGIO信号           signal(SIGIO, handler); 2)应用程序要指定进程为文件的属主,设置当前的文件描述为当前的调用进 ...

  9. .net的远程调用

    .Net远程调用(转自:http://www.cnblogs.com/omilan/articles/3191378.html) 看到了这.net远程调用的讲解,觉得不错,拿来分享!! .Net对于远 ...

  10. unity shadow

    这东西好难找LIGHT_ATTENUATION(a) shadow 的结果就在这个衰减里,这谁能猜的着,我一点点测出来的,reference也很难找 感谢这位http://blog.csdn.net/ ...