问题:

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: 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]

]

官方难度:

Medium

翻译:

给定一个长度为n的无序数组S和目标数字target,在数组S中找出4个整数a,b,c,d,使a+b+c+d=target。

找出所有的可能解,且解集中不包含重复项。

例子:

数组S:{ 1, 0, -1, 0, -2, 2},目标值target=0。

解集为[ [-1,0,0,1],[-2,-1,1,2],[-2,0,0,2] ]。

  1. 显然,本题是No.001(Two Sum),No.015(3Sum),No.016(3Sum Closest)更深一步的讨论。在解决这道问题时,不妨考虑一种解法,适用于5Sum,6Sum之后一系列的问题。我可以将这些问题总结归纳为:kSum问题,k>=2。
  2. 显然是需要使用递归,而递归的终点就是2Sum问题。
  3. 将递归方法独立出来,在进入递归之前,优先给数组排序(如k=2,这种做法会略微影响性能)。
  4. 2Sum问题,仍然使用夹逼的原则,同时维护两侧的previous值。增加优化策略:当前左值大于目标数且当前左值大于0,return;当2倍前左值大于目标值,或2倍当前右值小于目标值,return。
  5. 当k>2时,做类似2Sum的优化策略,将当前目标值-当前值,作为递归入参的目标值,同时传入当前索引值,进行递归。
  6. 获得递归的解集,循环加入当前值到解集中返回。
  7. 注意入参检查。

解题代码:

     public static List<List<Integer>> fourSum(int[] nums, int target) {
if (nums == null || nums.length < 4) {
throw new IllegalArgumentException("Input error");
}
Arrays.sort(nums);
return kSum(nums, 0, target, 4);
} private static List<List<Integer>> kSum(int[] nums, int startIndex, int target, int kSum) {
List<List<Integer>> result = new LinkedList<>();
// 递归终点是2Sum问题
if (kSum == 2) {
int left = startIndex, right = nums.length - 1;
int preLeft = Integer.MIN_VALUE, preRight = Integer.MIN_VALUE;
while (left < right) {
if (nums[left] > target && nums[left] > 0) {
return result;
}
if (2 * nums[left] > target || 2 * nums[right] < target) {
return result;
}
if (nums[left] == preLeft) {
left++;
continue;
}
if (nums[right] == preRight) {
right--;
continue;
}
int sum = nums[left] + nums[right];
if (sum == target) {
List<Integer> list = new LinkedList<>();
list.add(nums[left]);
list.add(nums[right]);
result.add(list);
}
if (sum < target) {
preLeft = nums[left];
left++;
} else {
preRight = nums[right];
right--;
}
}
} else {
// 大于2Sum问题,使用递归
int previous = Integer.MAX_VALUE;
for (int i = startIndex; i < nums.length - 1; i++) {
if (nums[i] > target && nums[i] > 0) {
return result;
}
// target值的范围超过k个极值
if (kSum * nums[i] > target || kSum * nums[nums.length - 1] < target) {
return result;
}
if (nums[i] == previous) {
continue;
}
int tempTarget = target - nums[i];
// 开启递归
List<List<Integer>> tempResult = kSum(nums, i + 1, tempTarget, kSum - 1);
for (List<Integer> a : tempResult) {
a.add(nums[i]);
result.add(a);
}
previous = nums[i];
}
}
return result;
}

fourSum

相关链接:

https://leetcode.com/problems/4sum/

https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/medium/Q018.java

PS:如有不正确或提高效率的方法,欢迎留言,谢谢!

No.018:4Sum的更多相关文章

  1. Python练习题 018:打印星号菱形

    [Python练习题 018] 打印出如下图案(菱形): * *** ***** ******* ***** *** * --------------------------------------- ...

  2. LeetCode第[18]题(Java):4Sum 标签:Array

    题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...

  3. C++笔记018:构造函数的调用规则

      原创笔记,转载请注明出处! 点击[关注],关注也是一种美德~ 一.默认构造函数 两个特殊的构造函数 1.默认无参构造函数 当类中没有定义构造函数时,编译器默认提供一个无参构造函数,并且其函数体为空 ...

  4. Python3练习题 018:打印星号菱形

    Python的内置方法 str.center(width [, fillchar]) 就能轻而易举打印出来:str即是数量不等的星号,width即是最大宽度(7个空格),默认填充字符fillchar就 ...

  5. 018:InnoDB 存储引擎、表空间

    目录 一.InnoDB 存储引擎 1. InnoDB的历史 2. InnoDB的特点 3. InnoDB存储引擎的文件 3.1 概述 3.2 InnoDB - 表空间 3.3 General表空间 3 ...

  6. LeetCode OJ:4Sum(4数字之和)

    Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = tar ...

  7. 018:include函数详解

    include函数详解(了解——虽然用的很少): include函数的用法,目前有三种使用方式: 1.include(module,namespace=None): module:子url的模块字符串 ...

  8. LeetCode18:4Sum

    Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = tar ...

  9. ELK学习实验018:filebeat收集docker日志

    Filebeat收集Docker日志 1 安装docker [root@node4 ~]# yum install -y yum-utils device-mapper-persistent-data ...

随机推荐

  1. atitit.TokenService v3 qb1  token服务模块的设计 新特性.docx

    atitit.TokenService v3 qb1  token服务模块的设计 新特性.docx 1.1. V3 新特性1 1.2. V2 新特性1 2. Token的归类1 3. Token的用途 ...

  2. salesforce 零基础学习(二十)简单APP制作

    本篇参考链接:https://developer.salesforce.com/trailhead/project/salesforce_developer_workshop 本篇讲述的是最简单的AP ...

  3. 【Discuz】云平台服务:出了点小错,由于站点ID/通信KEY等关键信息丢失导致Discuz!云平台服务出现异常

    提示信息 出了点小错,由于站点ID/通信KEY等关键信息丢失导致Discuz!云平台服务出现异常 版本X3.2.20160601 解决方案 Step1.修改云平台开通状态为未开通状态 Step2.访问 ...

  4. 深入理解CSS浮动

    × 目录 [1]定义 [2]特性 [3]表现 [4]重叠 前面的话 浮动最早的使用是出自<img src="#" align="right">,用于 ...

  5. java多线程执行问题

    class Demo extends Thread{ public Demo(String name){ super(name); } public void run(){ for(int i=0; ...

  6. c#socket同步通信

    再次特别感谢张子阳老师的文章,读后深感益处. 废话不多说,先贴代码 这是服务器端代码 using System; using System.Collections.Generic; using Sys ...

  7. Android Junit测试框架

    对应用进行单元测试: 使用Junit测试框架,是正规Android开发的必用技术.在Junit中可以得到组件,可以模拟发送事件和检测程序处理的正确性. 1.配置指令集和函数库: (1)配置指令集,指定 ...

  8. 轻松自动化---selenium-webdriver(python) (十)

    本节重点 处理下拉框 switch_to_alert() accept() 下拉框是我们最常见的一种页面元素,对于一般的元素,我们只需要一次就定位,但下拉框里的内容需要进行两次定位,先定位到下拉框,再 ...

  9. 在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误

    在visual studio 中添加数据库应用时,报错,提示如下: 在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误.未找到或无法访问服务器.请验证实例名称是否正确并且 SQL ...

  10. PHP类和对象函数实例详解

    1. interface_exists.class_exists.method_exists和property_exists: 顾名思义,从以上几个函数的命名便可以猜出几分他们的功能.我想这也是我随着 ...