4Sum

来源:互联网 发布:mac file文件夹在哪里 编辑:程序博客网 时间:2024/05/22 09:51

题目:
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)

思路:
1、和三个数之和两个数之和一样,只不过是多加了个循环而已;
代码:

class Solution {public:    vector<vector<int> > fourSum(vector<int> &num, int target) {        vector<vector<int>> res;        if(num.size()<4) return res;        sort(num.begin(),num.end());        int sum=0;        set<vector<int>> help;        for(int i=0;i<=num.size()-1;i++)        {            for(int j=i+1;j<=num.size()-1;j++)            {                int start=j+1;                int end=num.size()-1;                while(start<end)                {                    sum=num[i]+num[j]+num[start]+num[end];                    if(sum==target)                    {                        vector<int>tmp;                        tmp.push_back(num[i]);                        tmp.push_back(num[j]);                        tmp.push_back(num[start]);                        tmp.push_back(num[end]);                        //res.push_back(tmp);                        help.insert(tmp);                        start++;                        end--;                    }                    else if(sum<target) start++;                    else end--;                }            }        }        set<vector<int>> :: iterator it=help.begin();        for(;it!=help.end();it++)        {            res.push_back(*it);        }        return res;    }};
0 0
原创粉丝点击