Leetcode No18. 4sum_leetcode

Source: Internet
Author: User

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: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]


First sort, two-tier loops to determine two-digit nums[i],nums[j], then use two pointers m,n from I+1, Nums.size () forward Search

Note that during traversal, there are repeated accepted Code to be moved backwards:

Class Solution {public:vector<vector<int>> foursum (vector<int>& nums, int target) {ve
        ctor<vector<int>> Res;
        if (Nums.size () <4) return res;
        Sort (Nums.begin (), Nums.end ()); 
            for (int i=0;i<nums.size () -3;i++) {if (i>0&&nums[i]==nums[i-1]) continue; for (int j=i+1;j<nums.size () -2;j++) {if (j> (i+1) &&nums[j]==nums[j-1]
                ) continue;
                int m=j+1;
                int N=nums.size ()-1;
                        while (M < n) {if (m> (j+2) &&nums[m]==nums[m-1]) {
                    Continue } if (n< (Nums.size ()-1) &&nums[n]==nums[n+1]) {n
                }    int sum=nums[i]+nums[j]+nums[m]+nums[n];
                        if (sum==target) {vector<int> tmp={nums[i],nums[j],nums[m],nums[n]};
                        Res.push_back (TMP);
                    else if (sum>target) n--;
                else m++;
    }} return res; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.