leetcode-4Sum

来源:互联网 发布:手游网游 知乎 编辑:程序博客网 时间:2024/09/21 06:17

Given an array S of n integers, are there elements abc, 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)
bool compare(const int &a, const int &b){    return a<b;}class Solution {public:    vector<vector<int> > fourSum(vector<int> &num, int target) {        int n = num.size();        vector<vector<int> > ret;        if(n < 4)return ret;        sort(num.begin(),num.end(),compare);        for(int i = 0; i < n-2; i++)        {            if((i > 0)&&(num[i] == num[i-1]))continue;            for(int l = i+1; l < n-1; l++)            {                if((l > i+1)&&(num[l] == num[l-1]))continue;                int a = target-num[i]-num[l];                int j = l+1;                int k = n-1;                while(k > j)                {                    if(a == num[j]+num[k])                    {                        vector<int> temp;                        temp.push_back(num[i]);                        temp.push_back(num[l]);                        temp.push_back(num[j]);                        temp.push_back(num[k]);                        ret.push_back(temp);                        k--;                        j++;                        while((num[j]==num[j-1])&&(j < n))j++;                        while((num[k]==num[k+1])&&(k > -1))k--;                    }                    else if(a > num[j]+num[k])j++;                    else k--;                }                            }        }        return ret;       }};


0 0
原创粉丝点击