18. 4Sum

Medium (Trung bình) C++ 🔗 Xem trên LeetCode

📋 Đề Bài

Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

  • 0 <= a, b, c, d < n
  • a, b, c, and d are distinct.
  • nums[a] + nums[b] + nums[c] + nums[d] == target

You may return the answer in any order.

 

Example 1:

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

Example 2:

Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]

 

Constraints:

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

🧠 Thuật Toán & Kỹ Thuật

Two Pointers (Hai con trỏ)Bit Manipulation (Thao tác bit)
⏱️ Thời gian O(n²)
💾 Không gian O(n)

💻 Lời Giải

C++ 0018-4sum.cpp
using ll = long long;

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        int n = nums.size();
        set<vector<int>> us;
        sort(nums.begin(), nums.end());
        
        for (int a = 0; a < n - 3; ++a) {
            for (int b = a + 1; b < n - 2; ++b) {
                int c = b + 1;
                int d = n - 1;
                ll remaining = (ll)(target - (ll)(nums[a] + nums[b]));
                while (c < d) {
                    if ((ll)(nums[c] + nums[d]) == remaining) {
                        us.insert({nums[a], nums[b], nums[c], nums[d]});
                        c++;
                        d--;
                    }
                    else if (nums[c] + nums[d] > remaining) {
                        d--;
                    }
                    else {
                        c++;
                    }
                }
            }
        }
        
        vector<vector<int>> ans;
        
        for (const auto arr : us) {
            ans.push_back(arr);
        }
        
        return ans;
    }
};