LeetCode 18 - 4Sum

来源:互联网 发布:淘宝奥龙世博有假货吗 编辑:程序博客网 时间:2024/04/19 06:31

一、问题描述

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:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • 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)

给定一个包含 n 个整数的数组,以及一个目标整数 target,找出其中所有和等于 target 的四元组。

注意:

  • 每个四元组中的4个数按大小顺序排列,a ≤ b ≤ c ≤ d 。
  • 返回的四元组不能重复。


二、解题报告

K sum 是一类问题,在《LeetCode 15 - 3Sum》中说到:3Sum可以通过先固定一个数,从而转化为2Sum。

同理,4sum 也可以先固定一个数,转化成3sum问题;然后再固定一个数,最后也就是解决一个2sum的问题。

下面直接上代码:O(n3)

class Solution {    vector<vector<int>> res;public:    vector<vector<int>> fourSum(vector<int>& nums, int target) {        if(nums.size() < 4)            return res;        sort(nums.begin(), nums.end());   // 排序        for(int i=0; i<nums.size()-3; ++i) {            if(i>0 && nums[i]==nums[i-1]) // 相等的跳过                continue;            threeSum(nums, i+1, nums[i], target);        }        return res;    }    void threeSum(vector<int>& nums, int p, int first, int target) {        for(int i=p; i<nums.size()-2; ++i) {            if(i>p && nums[i]==nums[i-1]) // 相等的跳过                continue;            twoSum(nums, i+1, nums.size()-1, first, nums[i], target);        }    }    void twoSum(vector<int>& nums, int begin, int end, int first, int second, int target) {        int i = begin;  // 头指针        int j = end;    // 尾指针        while(i < j) {            if(first+second+nums[i]+nums[j]==target) {                vector<int> v;                v.push_back(first);                v.push_back(second);                v.push_back(nums[i]);                v.push_back(nums[j]);                res.push_back(v);                while(i<j && nums[i]==nums[i+1])                     ++i;  // 相等的跳过                while(i<j && nums[j]==nums[j-1])                     --j;  // 相等的跳过                ++i;                --j;            }            else if(first+second+nums[i]+nums[j]<target)                ++i;            else                --j;        }    }};





LeetCode答案源代码:https://github.com/SongLee24/LeetCode


0 0
原创粉丝点击