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

LeetCode:4Sum

时间:2014-06-05 00:34:06      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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, abcd)


  • 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)

解题思路:
    由于最终结果集中的四元组是非降序的,所以事先对序列进行排序,然后分别枚举c,d的位置.

去重的做法与3Sum的做法类似,只是多了一重循环.时间复杂度为O(N^3).

解题代码:
 
class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target)
    {
        sort(num.begin(),num.end());
        vector<vector<int> > res;
        int n = num.size() , arr[4] ;
        bool flag = false;
        for(int d = n - 1 ; d > 2 ; --d)
        {
            if( d < n - 1 && num[d] == num[d+1])
                continue;
            for(int c = d - 1 ; c > 1 ; --c)
            {
                if( c < d - 1 && num[c] == num[c+1])
                    continue;
                int a = 0 , b = c - 1 ;
                while( a < b)
                {
                    long long sum = num[a] + num[b] + num[c] + num[d] ;
                    if(sum == target)
                    {
                        if(!flag)
                        {
                            arr[0] = num[a] , arr[1] = num[b] , arr[2] = num[c] , arr[3] = num[d];
                            res.push_back(vector<int>(arr,arr+4));
                            flag = true;
                        }
                        else if(arr[0] != num[a] || arr[1] != num[b] || arr[2] != num[c] || arr[3] != num[d])
                        {
                            arr[0] = num[a] , arr[1] = num[b] , arr[2] = num[c] , arr[3] = num[d];
                            res.push_back(vector<int>(arr,arr+4));
                        }
                        ++a , --b ;
                        continue;
                    }
                    sum > target ? --b : ++a ;
                }
            }
        }
        return res;
    }
};


LeetCode:4Sum,布布扣,bubuko.com

LeetCode:4Sum

标签:leetcode

原文地址:http://blog.csdn.net/dream_you_to_life/article/details/27214191

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