题目链接 https://leetcode.com/problems/4sum/?tab=Description

找到数组中满足 a+b+c+d=0的所有组合,要求不重复。

Basic idea is using subfunctions for 3sum and 2sum, and keeping throwing all impossible cases. O(n^3) time complexity, O(1) extra space complexity.

首先进行判断,由于是四个数相加等于target,其中可以通过判断剪去一些不必要的分支:

for (i = 0; i < len; i++) {
z = nums[i];
if (i > 0 && z == nums[i - 1])// avoid duplicate
continue;
if (z + 3 * max < target) // z is too small
continue;
if (4 * z > target) // z is too large
break;
if (4 * z == target) { // z is the boundary
if (i + 3 < len && nums[i + 3] == z)
res.add(Arrays.asList(z, z, z, z));
break;
} threeSumForFourSum(nums, target - z, i + 1, len - 1, res, z);
}

进入3个数相加的同时,需要对target进行更新。

for (i = low; i < high - 1; i++) {
z = nums[i];
if (i > low && z == nums[i - 1]) // avoid duplicate
continue;
if (z + 2 * max < target) // z is too small
continue; if (3 * z > target) // z is too large
break; if (3 * z == target) { // z is the boundary
if (i + 1 < high && nums[i + 2] == z)
fourSumList.add(Arrays.asList(z1, z, z, z));
break;
} twoSumForFourSum(nums, target - z, i + 1, high, fourSumList, z1, z);
}

进入两个数相加时,问题得到进一步简化。

int i = low, j = high, sum, x;
while (i < j) {
sum = nums[i] + nums[j];
if (sum == target) {
fourSumList.add(Arrays.asList(z1, z2, nums[i], nums[j])); x = nums[i];
while (++i < j && x == nums[i]) // avoid duplicate
;
x = nums[j];
while (i < --j && x == nums[j]) // avoid duplicate
;
}
if (sum < target)
i++;
if (sum > target)
j--;
}

参考代码:

package leetcode_50;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; /***
*
* @author pengfei_zheng
* 四个数加法等于target
*/
public class Solution18 {
public List<List<Integer>> fourSum(int[] nums, int target) {
ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
int len = nums.length;
if (nums == null || len < 4) //不足4个元素
return res; Arrays.sort(nums);//排序 int max = nums[len - 1];
if (4 * nums[0] > target || 4 * max < target)//4个最小值之和超过target或者4个最大值之和小于target
return res; int i, z;
for (i = 0; i < len; i++) {
z = nums[i];
if (i > 0 && z == nums[i - 1])// avoid duplicate
continue;
if (z + 3 * max < target) // z is too small
continue;
if (4 * z > target) // z is too large
break;
if (4 * z == target) { // z is the boundary
if (i + 3 < len && nums[i + 3] == z)
res.add(Arrays.asList(z, z, z, z));
break;
} threeSumForFourSum(nums, target - z, i + 1, len - 1, res, z);
} return res;
} public void threeSumForFourSum(int[] nums, int target, int low, int high, ArrayList<List<Integer>> fourSumList,
int z1) {
if (low + 1 >= high)
return; int max = nums[high];
if (3 * nums[low] > target || 3 * max < target)
return; int i, z;
for (i = low; i < high - 1; i++) {
z = nums[i];
if (i > low && z == nums[i - 1]) // avoid duplicate
continue;
if (z + 2 * max < target) // z is too small
continue; if (3 * z > target) // z is too large
break; if (3 * z == target) { // z is the boundary
if (i + 1 < high && nums[i + 2] == z)
fourSumList.add(Arrays.asList(z1, z, z, z));
break;
} twoSumForFourSum(nums, target - z, i + 1, high, fourSumList, z1, z);
} } public void twoSumForFourSum(int[] nums, int target, int low, int high, ArrayList<List<Integer>> fourSumList,
int z1, int z2) { if (low >= high)
return; if (2 * nums[low] > target || 2 * nums[high] < target)
return; int i = low, j = high, sum, x;
while (i < j) {
sum = nums[i] + nums[j];
if (sum == target) {
fourSumList.add(Arrays.asList(z1, z2, nums[i], nums[j])); x = nums[i];
while (++i < j && x == nums[i]) // avoid duplicate
;
x = nums[j];
while (i < --j && x == nums[j]) // avoid duplicate
;
}
if (sum < target)
i++;
if (sum > target)
j--;
}
return;
}
}

Full Code

LeetCode 18 4Sum (4个数字之和等于target)的更多相关文章

  1. LeetCode 18. 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 ...

  2. [LeetCode] 454. 4Sum II 四数之和II

    Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such t ...

  3. [LeetCode] 18. 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 ...

  4. LeetCode——18. 4Sum

    一.题目链接:https://leetcode.com/problems/4sum/ 二.题目大意: 给定一个数组A和一个目标值target,要求从数组A中找出4个数来使之构成一个4元祖,使得这四个数 ...

  5. 18 4Sum(寻找四个数之和为指定数的集合Medium)

    题目意思:给一个乱序数组,在里面寻找三个数之和为target的所有情况,这些情况不能重复,增序排列 思路:采用3Sum的做法 ps:有见一种用hash的,存任意两个元素的和,然后变成3sum问题,需要 ...

  6. leetcode 18 4Sum JAVA

    题目 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出 ...

  7. [leetcode]18. 4Sum四数之和

    Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums s ...

  8. 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 ...

  9. [LeetCode] 18. 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 ...

随机推荐

  1. linux内置软件安装命令

    yum -y install epel-release

  2. Material Design Support 8大控件介绍

    TextInputLayout 显示提示信息 能够通过调用setError()在EditText以下显示一条错误信息 FloatingActionButton 悬浮操作按钮 Snackbar 相当于底 ...

  3. js 1+'2' == '1'+'2'

    前言 非常深入地讲解了包含隐式转换时js计算过程,全篇干货.本文由@keenjaan授权分享. 本文由@仙人掌推荐分享 正文从这里开始 你有没有在面试中遇到特别奇葩的js隐形转换的面试题,第一反应是怎 ...

  4. 按键精灵如何调用Excel及按键精灵写入Excel数据的方法教程---入门自动操作表格

    首先来建立一个新的Excel文档,在桌面上点击右键,选择[新建]-[Excel工作表],命名为[新手学员]. 现在这个新Excel文档是空白的,我们接下来会通过按键精灵的脚本来打开并写入一些数据.打开 ...

  5. EJB与JPA的关系

    转自:http://www.cnblogs.com/o-andy-o/archive/2012/04/17/2453537.html JPA是基于Java持久化的解决方案,主要是为了解决ORM框架的差 ...

  6. 【python】logging

    https://docs.python.org/3/howto/logging.html import logging # create logger logger = logging.getLogg ...

  7. PyCharm搭建pyqt5开发环境

    PyCharm搭建PyQt5开发环境 1.安装PyQt5 2.PyCharm环境配置 2.1 添加QtDesigner 2.2 添加PyUIC 2.3 添加Pyrcc 2.4 添加assistant ...

  8. node.js--Less

    摘要: 现在已经有许多站点使用Node.js,所以在Node.js上配置Less环境也是很重要的,下面分享下如何在Node上使用Less开发,前提是你电脑上已经安装node. 安装: 只需要执行下面一 ...

  9. [OpenCV] Image Processing - Grayscale Transform & Histogram

    颜色直方图 首先,先介绍一些Hist的基本使用. Ref:[OpenCV]数字图像灰度直方图 官方文档:https://docs.opencv.org/trunk/d8/dbc/tutorial_hi ...

  10. jumpserver安装及使用教程

    我自己是jumpserver的新手,以下两个链接是比较好的教程: 安装教程:http://blog.csdn.net/wanglei_storage/article/details/51001810 ...