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:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie,abcd)
  • 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> > result;
        int n = nums.size();
        if (n < 4)
        {
            return result;
        }
    
        sort(nums.begin(), nums.end());

        int i = 0;
        while (i < n-3)
        {
            if (i > 0 && nums[i] == nums[i-1])
            {
                i++;
                continue;
            }
            int j = i+1;
            while (j < n-2)
            {
                if (j > i+1 && nums[j] == nums[j-1])
                {
                    j++;
                    continue;
                }

                int sum = target - nums[i] - nums[j];
                int left = j+1;
                int right = n-1;
                while (left < right)
                {
                    int value = nums[left] + nums[right];
                    if (sum == value)
                    {
                        vector<int> temp;
                        temp.push_back(nums[i]);
                        temp.push_back(nums[j]);
                        temp.push_back(nums[left]);
                        temp.push_back(nums[right]);

                        result.push_back(temp);
                        left++;
                        while (left < right && nums[left] == nums[left-1])
                        {
                            left++;
                        }
                    }
                    else if (value > sum)
                    {
                        right--;
                        while (right > left && nums[right] == nums[right+1])
                        {
                            right--;
                        }
                    }
                    else
                    {
                        left++;
                        while (left < right && nums[left] == nums[left-1])
                        {
                            left++;
                        }
                    }
                }
                j++;
            }
            i++;
        }

        return result;
    }
};


你可能感兴趣的:(4Sum)