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.

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]
]

Difficulty: Medium

与这道题相似的还有Two Sum 两数之和等于一个输入的数, 15. 3Sum 三数之和, 16. 3Sum Closest 最近三数之和 解题思路基本一样. 可以在15. 3Sum 三数之和解法上再套一个for循环,复杂度为O(n^3)

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        set<vector<int>> res;
        sort(nums.begin(), nums.end());
        int n = nums.size();
        for (int i = 0; i < n-3; i++)
        {
            for (int j = i + 1; j < n-2;j++)
            {
                int left = j+1,right = n-1;
                while (left <right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum==target)
                    {
                        vector<int> out;
                        out.push_back(nums[i]);
                        out.push_back(nums[j]);
                        out.push_back(nums[left]);
                        out.push_back(nums[right]);
                        res.insert(out);
                        ++left;
                        --right;
                    }else if (sum <target)
                        left++;
                    else
                        right--;
                }
            }
        }
        return vector<vector<int>> (res.begin(),res.end());
    }
};
 
comments powered by Disqus