Leetcode-18. 4Sum

来源:互联网 发布:免费oa办公系统源码 编辑:程序博客网 时间:2024/06/02 06:22

题目:

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

思路

可以将4sum转成求3sum,进而转成求2sum,借助set实现无重复解。

代码

class Solution {public:    vector<vector<int> > fourSum(vector<int>& nums, int target) {        vector<vector<int> > result;        if(nums.size() < 4)            return result;        sort(nums.begin(), nums.end());        set<vector<int> > se;        int len = nums.size();        for(int i=0; i<len-3; i++){            for(int j=i+1; j<len-2; j++){                int begin=j+1;                int end=len-1;                while(begin<end){                    int sum=nums[i]+nums[j]+nums[begin]+nums[end];                    if(sum == target){                        vector<int> temp;                        temp.push_back(nums[i]);                        temp.push_back(nums[j]);                        temp.push_back(nums[begin++]);                        temp.push_back(nums[end--]);                        se.insert(temp);                    }else if(sum < target)                        begin++;                    else                        end--;                }            }           }        set<vector<int> >::iterator it;        for(it=se.begin(); it!=se.end();it++)            result.push_back(*it);        return result;    }};
0 0
原创粉丝点击