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

4Sum

时间:2014-06-04 22:44:27      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:des   c   style   class   blog   code   

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)
bubuko.com,布布扣
class Solution {
public:
    vector<vector<int>> fourSum(vector<int> &num, int target) 
    {
        vector<vector<int>> result;
        if(num.size()<4return result;
        
        sort(num.begin(),num.end());
        for(int i1=0;i1<num.size();i1++)
        {
            if(i1>0 && num[i1]==num[i1-1])
                continue;
            for(int i2=i1+1;i2<num.size();i2++)
            {
                if(i2>i1+1 && num[i2]==num[i2-1])
                    continue;
                int i3=i2+1;
                int i4=num.size()-1;
                while(i3<num.size() && i4<num.size() && i3<i4)
                {
                    if(num[i3]+num[i4]==target-num[i1]-num[i2])
                    {
                        vector<int> v;
                        v.push_back(num[i1]);v.push_back(num[i2]);v.push_back(num[i3]);v.push_back(num[i4]);
                        result.push_back(v);
                        do
                        {
                            i3++;
                        }while(i3<num.size()&& num[i3]==num[i3-1]);
                        do
                        {
                            i4--;
                        }while(i4>i3 && num[i4]==num[i4+1]);
                    }
                    else if(num[i3]+num[i4]<target-num[i1]-num[i2])
                        i3++;
                        else i4--;
                }
            }
        }
        return result;
    }
};
bubuko.com,布布扣

4Sum,布布扣,bubuko.com

4Sum

标签:des   c   style   class   blog   code   

原文地址:http://www.cnblogs.com/erictanghu/p/3759258.html

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