码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode[18]4Sum

时间:2015-02-10 14:47:48      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

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)
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 c,d;
        for(int a=0;a<num.size();a++)
        {
            if(a>0&&num[a]==num[a-1])
            continue;
            for(int b=a+1;b<num.size();b++)
            {
                if(b>a+1&&num[b]==num[b-1])
                continue;
                c=b+1;
                d=num.size()-1;
                while(c<d)
                {
                    if(c>b+1&&num[c]==num[c-1])
                    {
                        c++;
                        continue;
                    }
                    if(d<num.size()-1&&num[d]==num[d+1])
                    {
                        d--;
                        continue;
                    }
                    int sum=num[a]+num[b]+num[c]+num[d];
                    if(sum<target)c++;
                    else if(sum>target)d--;
                    else
                    {
                        vector<int> temp;
                        temp.push_back(num[a]);
                        temp.push_back(num[b]);
                        temp.push_back(num[c]);
                        temp.push_back(num[d]);
                        res.push_back(temp);
                        c++;
                        d--;
                    }
                }
            }
        }
        return res;
    }
};

 

leetcode[18]4Sum

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4283673.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!