[Leetcode] 4Sum

Posted yanhewu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] 4Sum相关的知识,希望对你有一定的参考价值。

4Sum 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/4sum/description/


Description

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.

Example


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


class Solution {
private:
    vector<vector<int> > twoSum(vector<int>& nums, int end, int target) {
        vector<vector<int> > res;
        int low = 0;
        int high = end;
        while (low < high) {
            if (nums[low] + nums[high] == target) {
                vector<int> sum(2);
                sum[0] = nums[low++];
                sum[1] = nums[high--];
                res.push_back(sum);

                // 去重
                while (low < high && nums[low] == nums[low - 1])
                    low++;
                while (low < high && nums[high] == nums[high + 1])
                    high--;
            } else if (nums[low] + nums[high] > target) {
                high--;
            } else {
                low++;
            }
        }
        return res;
    }

    vector<vector<int> > threeSum(vector<int>& nums, int end, int target) {
        vector<vector<int>> res;
        if (end < 2)
            return res;
        sort(nums.begin(), nums.end());
        for (int i = end; i >= 2; i--) {
            if (i < end && nums[i] == nums[i + 1])  // 去重
                continue;
            auto sum2 = twoSum(nums, i - 1, target - nums[i]);
            if (!sum2.empty()) {
                for (auto& sum : sum2) {
                    sum.push_back(nums[i]);
                    res.push_back(sum);
                }
            }
        }
        return res;
    }
public:
    vector<vector<int> > fourSum(vector<int>& nums, int target) {
        vector<vector<int>> res;
        int size = nums.size();
        if (size < 4)
            return res;
        sort(nums.begin(), nums.end());
        for (int i = size - 1; i >= 2; i--) {
            if (i < size - 1 && nums[i] == nums[i + 1])  // 去重
                continue;
            auto sum3 = threeSum(nums, i - 1, target - nums[i]);
            if (!sum3.empty()) {
                for (auto& sum : sum3) {
                    sum.push_back(nums[i]);
                    res.push_back(sum);
                }
            }
        }
        return res;
    }
};

解题描述

这道题可以说是3Sum的再次进阶,使用的方法和3Sum基本相同,只是在求3个数之和之后再套上一层循环。时间复杂度为O(n^3)。

以上是关于[Leetcode] 4Sum的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] 4Sum

leetcode 18 4Sum

LeetCode——18. 4Sum

LeetCode - 18. 4Sum

Leetcode018 4Sum

LeetCode(16. 4Sum)