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

LeetCode 18 4Sum(4个数的和)

时间:2015-10-18 12:55:33      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:c语言   leetcode   x   sum   vector   

翻译

给定一个有n个数字的数组S,在S中是否存在元素a,b,c和d的和恰好满足a + b + c + d = target。

找出数组中所有的不想等的这四个元素,其和等于target。

备注:

在(a,b,c,d)中的元素必须从小到大排列。(a ≤ b ≤ c ≤ d)
其结果必须不能够重复。

例如,给定S = {1 0 -1 0 -2 2},target = 0。
一个结果集为:
(-1,  0, 0, 1)
(-2, -1, 1, 2)
(-2,  0, 0, 2)

原文

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)

代码

具体的方法和前面两道题一样,我就不再赘述了。

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums,int target) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> result;

        int len = nums.size();      
        for (int current = 0; current < len - 3;current++)
        {
            for(int second = current+1;second<len-2;second++)
            {
                int front = second + 1, back = len - 1;
                while (front < back)
                {
                    if (nums[current]+nums[second] + nums[front] + nums[back]  < target)
                        front++;
                    else if (nums[current] +nums[second]+ nums[front] + nums[back] > target)
                        back--;
                    else
                    {
                        vector<int> v(4);
                        v[0]=nums[current];
                        v[1]=nums[second];
                        v[2]=nums[front];
                        v[3]=nums[back];
                        result.push_back(v);
                        do {
                            front++;
                        } while (front < back&&nums[front - 1] == nums[front]);
                        do {
                            back--;
                        } while (front < back&&nums[back + 1] == nums[back]);
                    }
                } 
                while(second < len-2&&nums[second+1]==nums[second])
                    second++;
            }                               
            while (current < len - 3 && nums[current + 1] == nums[current])
                current++;
        }                                  
        return result;
    }
};

和本道题关联密切的题目推荐:

传送门:LeetCode 15 3Sum(3个数的和)
传送门:LeetCode 16 3Sum Closest(最接近的3个数的和)

版权声明:本文为 NoMasp柯于旺 原创文章,未经许可严禁转载!欢迎访问我的博客:http://blog.csdn.net/nomasp

LeetCode 18 4Sum(4个数的和)

标签:c语言   leetcode   x   sum   vector   

原文地址:http://blog.csdn.net/nomasp/article/details/49226833

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