其他分享
首页 > 其他分享> > Leetcode 18. 4sum

Leetcode 18. 4sum

作者:互联网

题目描述

给出一个有n个元素的数组S,S中是否有元素a,b,c和d满足a+b+c+d=目标值?找出数组S中所有满足条件的四元组。 注意:
  1. 四元组(a、b、c、d)中的元素必须按非降序排列。(即a≤b≤c≤d)
  2. 解集中不能包含重复的四元组。
    例如:给出的数组 S = {1 0 -1 0 -2 2}, 目标值 = 0.↵↵    给出的解集应该是:↵    (-1,  0, 0, 1)↵    (-2, -1, 1, 2)↵    (-2,  0, 0, 2)
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:

 

    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)

继续套用2sum的思想,先两层循环,然后最后两位用夹逼,注意判断重复
class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        int n=num.size();
        sort(num.begin(),num.end());
        vector<vector<int>> res;
        for(int i=0;i<n;++i)
        {
            if(i>0&&num[i]==num[i-1])
                continue;
            int t1 = target-num[i];
            for(int j=i+1;j<n;++j)
            {
                if(j>i+1&&num[j]==num[j-1])
                    continue;
                int t2 = t1-num[j];
                int l=j+1,r=n-1;
                while(l<r)
                {
                    int t3 =t2-num[l]-num[r];
                    if(t3==0)
                    {
                        res.push_back({num[i],num[j],num[l],num[r]});
                        while(l<r&&num[l]==num[l+1]) l++;
                        while(l<r&&num[r]==num[r-1]) r--;
                        l++;r--;
                    }
                    else if(t3 >0) l++;
                    else r--;
                }
            }
        }
        return res;
    }
};

 

标签:4sum,vector,target,int,18,四元组,num,array,Leetcode
来源: https://www.cnblogs.com/zl1991/p/12783091.html