4Sum

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)
中文,求四个数的和,让其等于目标数。
分析:和3sum类似。

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> result;
        vector<int> four;
        sort(nums.begin(),nums.end());
        int i,j,k,t;
        int sum=0;
        int n=nums.size();
        for(i=0;i<n;i++)
        {
            if(i>0&&nums[i]==nums[i-1])
            continue;

            for(j=i+1;j<n;j++)
            {
                if(j>i+1&&nums[j]==nums[j-1])
                continue;
                k=j+1;
                t=n-1;
                while(k<t)
                {   
                    if(k>j+1&&nums[k]==nums[k-1])
                    {
                     k++;
                     continue;    
                    }
                   // if(t<n-1&&nums[t]==nums[t+1])
                   // {
                   //  t--;
                   //  continue;    
                  //  }
                    sum=nums[i]+nums[j]+nums[k]+nums[t];
                    if(sum==target)
                    {
                        four.push_back(nums[i]);
                        four.push_back(nums[j]);
                        four.push_back(nums[k]);
                        four.push_back(nums[t]);
                        result.push_back(four);
                        four.clear();
                        k++;
                    }
                    if(sum<target)
                    {
                       k++; 
                    }
                     if(sum>target)
                    {
                        t--;
                    }
                }
            }



        }
        return result;
    }
};
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014734779/article/details/46818819
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

4Sum

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭