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. Guess Number Higher or Lower II -- LeetCode

    We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to gues ...

  2. [BZOJ3237][AHOI2013]连通图(分治并查集)

    3237: [Ahoi2013]连通图 Time Limit: 20 Sec  Memory Limit: 512 MBSubmit: 1736  Solved: 655[Submit][Status ...

  3. C# html的Table导出到Excel中

    C#中导出Excel分为两大类.一类是Winform的,一类是Web.今天说的这一种是Web中的一种,把页面上的Table部分导出到Excel中. Table导出Excel,简单点说,分为以下几步: ...

  4. Microsoft Office Excel 2007 使用笔记

    1.显示表格边框: 选择要显示边框的单元格,点击“开始”选项卡中的“边框”图标,选中下拉框中的“所有框线” 2.单元格内,文字自动换行: 点击“开始”选项卡中的“自动换行”按钮 3.单元格内,文字手动 ...

  5. CSS限制

    http://www.cnblogs.com/YanPSun/archive/2012/03/16/2400141.html

  6. [置顶] kubernetes资源对象--ConfigMap

    原理 很多生产环境中的应用程序配置较为复杂,可能需要多个config文件.命令行参数和环境变量的组合.使用容器部署时,把配置应该从应用程序镜像中解耦出来,以保证镜像的可移植性.尽管Secret允许类似 ...

  7. 自助采样法 bootstrap 与 0.632

  8. Playonlinux

    apt-get install playonlinux -y apt-get install winbind -y apt-get install unzip -y 开始中搜索:playonlinux ...

  9. hive 导入csv文件

    创建hive表: create table table_name( id string, name string, age string ) row format serde 'org.apache. ...

  10. linux文件测试操作

    1.文件测试操作 返回 true 如果... -e 文件存在 -a 文件存在 这个选项的效果与-e 相同.但是它已经被弃用了,并且不鼓励使用 -f file 是一个 regular 文件(不是目录或者 ...