ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Leetcode 18. 4sum

2020-04-26 23:02:19  阅读:277  来源: 互联网

标签:4sum vector target int 18 四元组 num array Leetcode


题目描述

给出一个有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:

  • 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.↵↵    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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有