首页 > 代码库 > [leetcode-18-4Sum]

[leetcode-18-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.
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]
]

思路:

类似3sum求和,然后在过程中及时约束,判断是否可以提前跳出循环来优化。

vector<vector<int>> fourSum(vector<int>& nums, int target)
    {
        vector<vector<int>>result;
        const int size = nums.size();
        if (size < 4) return result;
        sort(nums.begin(), nums.end());
        vector<int>temp;
        for (int i = 0; i < size - 3; i++)
        {
            if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break;//及时跳出循环
            if (nums[i] + nums[size - 3] + nums[size - 2] + nums[size - 1] < target)continue;
            
            for (int j = i + 1; j < size-2; j++)
            {
                if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) break;//及时跳出循环
                if (nums[i] + nums[j] + nums[size - 2] + nums[size - 1] < target)continue;
                 
                int left = j + 1;
                int right = size - 1;
                while (left < right)
                {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum < target)left++;
                    else if (sum > target) right--;
                    else
                    {
                        temp = {nums[i],nums[j],nums[left],nums[right]};//新学一招,类似数组赋值
                        result.push_back(temp);
                        while (left < right && nums[left] == temp[2])left++;
                        while (left < right && nums[right] == temp[3])right--;
                    }         
                }
                while (j + 1 < size && nums[j + 1] == nums[j])j++;
            }
            while (i + 1 < size && nums[i + 1] == nums[i])i++;
        }
        return result;
    }

参考:

http://cs-cjl.com/2016/07_04_leetcode_18_4sum

[leetcode-18-4Sum]