18. 4Sum

Problem statement:

Given an array S of n integers, are there elements abc, 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]
]

Solution:

No, it is the 4sum problem, more dimension than 3sum. But, they are the same idea.

Time complexity O(n * n * n)

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        // divide it into two sum problem
        int size = nums.size();
        vector<vector<int>> quadruplets;
        sort(nums.begin(), nums.end());
        for(int i = 0; i < size - 3; i++){
            for(int j = i + 1; j < size - 2; j++){
                int left = j + 1;
                int right = size - 1;
                while(left < right){
                    if(nums[i] + nums[j] + nums[left] + nums[right] == target){
                        quadruplets.push_back({nums[i], nums[j], nums[left], nums[right]});
                        while(left < right && nums[right - 1] == nums[right]){
                            right--;
                        }
                        right--;
                        while(left < right && nums[left] == nums[left + 1]){
                            left++;
                        }
                        left++;
                    } else if (nums[i] + nums[j] + nums[left] + nums[right] > target) {
                        while(left < right && nums[right - 1] == nums[right]){
                            right--;
                        }
                        right--;
                    } else {
                        while(left < right && nums[left] == nums[left + 1]){
                            left++;
                        }
                        left++;
                    }
                }
                while(j + 1 < size && nums[j] == nums[j + 1]){
                    j++;
                }
            }
            while(i + 1 < size && nums[i] == nums[i + 1]){
                i++;
            }
        }
        return quadruplets;
    }
};
原文地址:https://www.cnblogs.com/wdw828/p/6883932.html