题目链接 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. tp5的学习

    1.安装,官网下载 2.访问配置:http://localhost/App/public/ 3.入口文件,项目目录/public // 定义应用目录 define('APP_PATH', __DIR_ ...

  2. 启动zookeeper时出现的问题

    zkEnv.cmd @echo off REM Licensed to the Apache Software Foundation (ASF) under one or more REM contr ...

  3. Objective-C语法之指针型参数

    main.m #import <Foundation/Foundation.h> /** * 测试指针型参数和普通参数的区别 * * @param a 指针型参数 * @param b 普 ...

  4. 到底什么时候才需要在ObjC的Block中使用weakSelf/strongSelf

    转载,原文: http://blog.lessfun.com/blog/2014/11/22/when-should-use-weakself-and-strongself-in-objc-block ...

  5. android LinearLayout添加分隔线

    方法一: 可以放置一个ImageView组件,然后将其设为分隔线的颜色或图形. 分隔线View的定义代码如下: [html] view plaincopy   <ImageView androi ...

  6. thinkphp 在阿里云上的nginx.config配置

    # For more information on configuration, see: # * Official English Documentation: http://nginx.org/e ...

  7. golang 内存分析/动态追踪

    如果你的go程序是用http包启动的web服务器,你想查看自己的web服务器的状态.这个时候就可以选择net/http/pprof.你只需要引入包_"net/http/pprof" ...

  8. 马尔科夫链蒙特卡洛(Markov chain Monte Carlo)

    (学习这部分内容大约需要1.3小时) 摘要 马尔科夫链蒙特卡洛(Markov chain Monte Carlo, MCMC) 是一类近似采样算法. 它通过一条拥有稳态分布 \(p\) 的马尔科夫链对 ...

  9. Maven 多项目依赖,需要验证artifact的output root中是否包含其他项目输出

  10. flask操作mongo两种方式--常规

    #manage.py #coding=utf-8 #Flask-Script是一个可以在flask应用外部编写脚本的扩展 #常用功能: #运行一个开发的服务器 #python shell中操作数据库看 ...