4Sum

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) {
        vector<vector<int>> res;
        int n = nums.size();

        sort(nums.begin(), nums.end());

        if(n < 4)   return {};

        for(int i = 0; i < n - 3; i++)
        {
            if(i > 0 && nums[i] == nums[i - 1])
                continue;
            for(int j = i + 1; j < n-2; j++)
            {
                //重要,从i+1开始哦
                if(j > i + 1 && nums[j] == nums[j - 1])
                    continue;
                int st = j + 1, en = n - 1;
                int twoSum = target - nums[i] -nums[j];
                while(st < en)
                {
                    int sum = nums[st] + nums[en];
                    if(sum == twoSum)
                    {
                        vector<int> temp;
                        temp.push_back(nums[i]);
                        temp.push_back(nums[j]);
                        temp.push_back(nums[st]);
                        temp.push_back(nums[en]);
                        res.push_back(temp);
                        st++;
                        en--;
                        while(st < en && nums[st] == nums[st - 1])
                            st++;
                        while(st < en && nums[en] == nums[en + 1])
                            en--;
                    }else if(sum < twoSum)
                        st++;
                    else
                        en--;
                }
            }
        }

        return res;
    }
};

results matching ""

    No results matching ""