博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 18: 4Sum
阅读量:4150 次
发布时间:2019-05-25

本文共 1058 字,大约阅读时间需要 3 分钟。

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)

代码如下:

class Solution {public:    vector
> fourSum(vector
&num, int target) { vector
> out; set
> res; if (num.size() < 4) return out; sort(num.begin(), num.end()); for (int i=0; i
tmp; tmp.push_back(num[i]); tmp.push_back(num[j]); tmp.push_back(num[begin]); tmp.push_back(num[end]); res.insert(tmp); begin++; end--; } else if(sum < target) { begin++; }else{ end--; } } } } set
>::iterator it = res.begin(); for(; it != res.end(); it++) out.push_back(*it); }};

转载地址:http://nbxti.baihongyu.com/

你可能感兴趣的文章
实验5-5 循环的合并
查看>>
实验5-6 do-while循环结构
查看>>
实验5-7 程序调试入门
查看>>
实验5-8 综合练习
查看>>
第2章实验补充C语言中如何计算补码
查看>>
深入入门正则表达式(java) - 命名捕获
查看>>
使用bash解析xml
查看>>
android系统提供的常用命令行工具
查看>>
【Python基础1】变量和字符串定义
查看>>
【Python基础2】python字符串方法及格式设置
查看>>
【Python】random生成随机数
查看>>
【Python基础3】数字类型与常用运算
查看>>
Jenkins迁移jobs
查看>>
【Python基础4】for循环、while循环与if分支
查看>>
【Python基础5】列表和元组
查看>>
【Python基础6】格式化字符串
查看>>
【Python基础7】字典
查看>>
【Python基础8】函数参数
查看>>
【Python基础9】浅谈深浅拷贝及变量赋值
查看>>
Jenkins定制一个具有筛选功能的列表视图
查看>>