问题:

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. redis常用操作总结

    在项目中时常会用到redis,redis看起来好像很难的样子,而且我也确认反复学习了很久,但是,总结下来,自己使用到的东西并不太多,如下作一些总结工作. 1.安装(单机) 1.1 windows, 直 ...

  2. mysql 的简单优化

    合理的建立索引的建议: (1)  越小的数据类型通常更好:越小的数据类型通常在磁盘.内存和CPU缓存中都需要更少的空间,处理起来更快. (2)  简单的数据类型更好:整型数据比起字符,处理开销更小,因 ...

  3. 更新日志 - BugHD 新增邮件告警功能

    最近 BugHD 又新增了一些功能,包括邮件告警. issue 分享. issue 备注等,同时也做了性能优化.希望能够帮助你更高效地收集解决应用崩溃. BugHD 新增功能 1.邮件告警 除了 We ...

  4. ToString()的各种用法(大全)

    常用例子: string str = ""; str = .ToString("N"); //生成 12,3456.00 str = .ToString(&qu ...

  5. 每天一个linux命令(33):df 命令

    linux中df命令的功能是用来检查linux服务器的文件系统的磁盘空间占用情况.可以利用该命令来获取硬盘被占用了多少空间,目前还剩下多少空间等信息. 1.命令格式: df [选项] [文件] 2.命 ...

  6. css基础总结一

    最近在弄一个简单管理系统的前端,所以打算将做项目的一些个人感想以及总结简单罗列下,当然,主要针对前端的基础部分以及一些常用的前端个人简单技巧总结.主要分为js部分和css部分,下面是css的基础部分总 ...

  7. 信息加密之非对称加密算法RSA

    前面为大家已经总结了,基于密钥交换的DH算法,现在就为大家再介绍一种基于因子分解的RSA算法,这种加密算法有两种实现形式:1.公钥加密,私钥解密:2.私钥加密,公钥解密.下面就为大家分析一下实现代码, ...

  8. jsp实现简单的分页

    效果如下:<%-- Document : page Created on : 2014-11-18, 8:55:02 Author : HJZ --%> <%@page conten ...

  9. 使用Ambari安装hadoop集群

    最近需要做些spark的工作,所以弄了几台dell7500就这么准备开始搭建集群,之前用过几台更破的台式机搭建过一次,折腾了半个月之久,终于成功搭建,这次不想走老路,所以网上查了一下,发现一个神器AM ...

  10. spring aop源码实现分析

    1. 先分析Advice before执行Cglib2AopProxy的intercept方法: /** * General purpose AOP callback. Used when the t ...