[Leetcode] 4Sum

给定一个整数数组S,寻找四个元素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)。利用已有的2Sum和3Sum思想,将4Sum问题转化为3Sum求解,同时避免重复结果。" 122494715,9101549,Vue项目中token与axios封装实践,"['vue.js', '前端开发', 'javascript']
摘要由CSDN通过智能技术生成

题目

Given anarray S of n integers, are thereelements a, b, c, and d in S suchthat a + b + c + d = target? Find allunique 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, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.

   For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

 

    Asolution set is:

   (-1,  0, 0, 1)

   (-2, -1, 1, 2)

   (-2,  0, 0, 2)

 

思路

有了2Sum,3Sum的基础,这道题不难。前面在解决3Sum的时候转化为2Sum来求解,这里同样可以把4Sum转化为3Sum来求解,需要注意的是去除重复结果。

 

代码

public class Solution {
    List<List<Integer>> result =new ArrayList<List<Integer>>();
    public List<List<Integer>>fourSum(int[] nums, int target) {
        if (nums == null)
            return result;
        int len = nums.length;
        if (len < 4)
            return result;
        Arrays.sort(nums);
       
        for (int i = 0; i < len - 3; i++) {
            if (i > 0 && nums[i] ==nums[i-1])
                continue;
            threeSum(nums, i + 1, len - 1,target, nums[i]);
        }
        return result;
    }
   
    public void threeSum(int[] nums, int l, intr, int target, int num1) {
        for (int i = l; i <= r - 2; i++) {
            if (i > l && nums[i] ==nums[i-1])
                continue;
            twoSum(nums, i + 1, r, target,num1, nums[i]);
        }
    }
   
    public void twoSum(int[] nums, int l, intr, int target, int num1, int num2){
        while (l < r) {
            if (num1 + num2 + nums[l] + nums[r]== target) {
                List<Integer> list = newArrayList<Integer>();
                list.add(num1);
                list.add(num2);
                list.add(nums[l]);
                list.add(nums[r]);
                result.add(list);
                while (l < r && nums[l] ==nums[l+1])
                    l++;
                while (l < r &&nums[r] == nums[r-1])
                    r--;
                l++;
                r--;
            }else if (num1 + num2 + nums[l] +nums[r] < target) {
                l++;
            }else {
                r--;
            }
        }
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值