Find unique triples that satisfy the condition

describe

Given an array (stored in vector form), find three numbers a, b and c from it, so that a+b+c=0 (a<=b<=c), the three numbers form a tuple (a, b, c). Now it is required to find all sequences of tuples that satisfy the sum of the three numbers equal to 0 (sort from small to large according to the first component, if the first component is the same, sort by the second component, if the second component is also the same, by the third component), the tuples in the sequence are unique (i.e., at least one component differs).

{-1, 0, 1, 2, -1, -4}

The result returned is the following sequence:

(-1, -1, 2)

(-1,  0, 1)

The code of the title part has been completed, you only need to add and submit the following functions:

vector< vector<int> > threeSum(vector<int>& nums);

enter

Enter the first row of n (3<=n<=200), which represents the number of array elements.

The second line has n integers.

output

Sort according to the title requirements, and output all tuples, one per line.

The components of the tuple are separated by spaces.

Data guarantees that at least one tuple exists.

sample input

6
-1 0 1 2 -1 -4

Sample output

-1 -1 2
-1 0 1

#include<bits/stdc++.h>
using namespace std;
vector<vector<int> >threeSum(vector<int>&nums)
{
    int s=0,i,j,k;
    set<vector<int> >se;
    set<vector<int> >::iterator it;
    
    vector<int>m;
    vector<vector<int> >x;
    for(i=0;i<nums.size()-2;i++)
    {
        for(j=i+1;j<nums.size()-1;j++)
        {
            for(k=j+1;k<nums.size();k++)
            {
                if(nums[i]+nums[j]+nums[k]==0)
                {
                    m.push_back(nums[i]);
                    m.push_back(nums[j]);
                    m.push_back(nums[k]);
                    sort(m.begin(),m.end());
                    se.insert(m);
                    m.clear();
                }        
            }
        }
    }
    for(it=se.begin();it!=se.end();it++)
        x.push_back(*it);
    return x;
}
intmain ()
{
    int n,i,j,a;
    vector<int>nums;
    vector<vector<int> >x;
    
    cin>>n;
    while(n--)
    {
        cin>>a;
        nums.push_back(a);
    }
    x=threeSum(nums);
    for(i=0;i<x.size();i++)
    {
        for(j=0;j<x[i].size();j++)
        {
            if(i==0)
                printf("%d",x[i][j]);
            else printf(" %d",x[i][j]);
        }
        printf("\n");
    }
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325329537&siteId=291194637