18. 4Sum

来源:互联网 发布:淘宝营销培训 编辑:程序博客网 时间:2024/06/06 00:44

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

题意:双指针类型

class Solution {public:    vector<vector<int>> fourSum(vector<int>& nums, int target) {        set<vector<int>> vec;        int sz = nums.size();        sort(nums.begin(), nums.end());        for(int i = 0; i < sz; ++i){            for(int j = i + 1; j < sz; ++j){                int l = j + 1, r = sz - 1;                int fix = nums[i] + nums[j];                while(l < r){                    int var = nums[l] + nums[r];                    if(fix + var == target){                        vec.insert({nums[i], nums[j], nums[l], nums[r]});                        ++l;                        --r;                    } else if(fix + var < target)                        ++l;                        else if(fix + var > target)                            --r;                }            }        }        return vector<vector<int>>(vec.begin(), vec.end());    }};