#The way to brush questions with leetcode 18-sum of four numbers

Posted by Hagbard on Sun, 01 Dec 2019 03:11:59 +0100

Given a n array of N integers nums a n d a target value target, judge whether there are four elements a, b, c and D in nums, so that the value of a + b + c + d is equal to target? Find all quads that meet the conditions and are not repeated.
Be careful:
The answer cannot contain duplicate quads.

Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
The set of quads that meet the requirements is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

Train of thought: violent solution, only optimize the last number temporarily

#include <iostream>
#include<vector>
#include <algorithm>
#include <set>
using namespace std;
vector<vector<int>> fourSum(vector<int>& nums, int target) {
    vector<vector<int>> ans;
    set<vector<int>> t;
    sort(nums.begin(),nums.end());
    int len=nums.size();
    for(int i=0;i<len-3;i++)
    {
        for(int j=i+1;j<len-2;j++)
        {
            for(int k=j+1;k<len-1;k++)
            {
                for(int h=k+1;h<len;h++)
                {
                    while ((h+1)<len&&nums[h]==nums[h+1]) h++;
                    if((nums[i]+nums[j]+nums[k]+nums[h])==target)
                    {
                        vector<int> temp;
                        temp.push_back(nums[i]);
                        temp.push_back(nums[j]);
                        temp.push_back(nums[k]);
                        temp.push_back(nums[h]);
                        int tt=t.size();
                        t.insert(temp);
                        if(tt!=t.size()) ans.push_back(temp);
                    }
                }
            }
        }
    }
    return ans;
}

int main() {
    vector<int> a={1,0,-1,0,-2,2};
    int target=0;
    vector<vector<int>> ans=fourSum(a,target);
    cout<<ans.size()<<endl;
    return 0;
}

Topics: C