18. 4Sum(Leetcode每日一題-2020.10.05)

Bryan要加油發表於2020-10-07

Problem

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Notice that the solution set must not contain duplicate quadruplets.

Constraints:

  • 0 <= nums.length <= 200
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/4sum
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

Example1

Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Example2

Input: nums = [], target = 0
Output: []

Solution

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> res;
        for (int i = 0; i < nums.size(); i ++ ) 
        {
            if (i && nums[i] == nums[i - 1]) 
                continue;
            for (int j = i + 1; j < nums.size(); j ++ ) 
            {
                if (j > i + 1 && nums[j] == nums[j - 1]) 
                    continue;
                for (int k = j + 1, u = nums.size() - 1; k < u; k ++ ) 
                {
                    if (k > j + 1 && nums[k] == nums[k - 1]) 
                        continue;
                    while (u - 1 > k && nums[i] + nums[j] + nums[k] + nums[u - 1] >= target) 
                        u -- ;
                    if (nums[i] + nums[j] + nums[k] + nums[u] == target) 
                    {
                        res.push_back({nums[i], nums[j], nums[k], nums[u]});
                    }
                }
            }
        }

        return res;
    }
};


相關文章