leetcode第17题--4Sum

Problem: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)

这题其实就是之前的变种,我是这样想的,首先还是排序好,然后根据固定四个的头和尾,即i为头,从0开始到倒数第四个,j为尾巴从尾开始到i+2. 再来一个left=i+1 right=j-1 如果i++之后和前面一个相等,那就直接continue,因为已经在之前一个i算过了,同理,j--之后如果和之前的j相等的话也是不用计算的直接continue 这样的话复杂度就是n3方

class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target)
{
    vector<vector<int> > sum;
    sum.clear();
    if(num.size() < 4)
        return sum;
    sort(num.begin(), num.end());

    for (int i = 0; i < num.size() - 3; ++i)
    {
        if (i - 1 >=0 && num[i - 1] == num[i])
            continue;
        for (int j = num.size() - 1; j > i + 2; --j)
        {
            if(j + 1 < num.size() && num[j + 1] == num[j])
                continue;
            int left = i + 1, right = j - 1;
            while(left < right)
            {
                if (num[i] + num[left] + num[right] + num[j] == target)
                    {
                        if(sum.size()==0 || sum.size()>0 && !(sum[sum.size() - 1][0]==num[i] && sum[sum.size() - 1][1]==num[left] && sum[sum.size() - 1][2]==num[right]))
                        {
                            vector<int> tep;
                            tep.push_back(num[i]);
                            tep.push_back(num[left]);
                            tep.push_back(num[right]);
                            tep.push_back(num[j]);
                            sum.push_back(tep);
                        }
                        left++;
                        right--;
                    }
                else if (num[i] + num[left] + num[right] + num[j] < target)
                    left++;
                else if (num[i] + num[left] + num[right] + num[j] > target)
                    right--;
            }
        }
    }
    return sum;
}
};
原文地址:https://www.cnblogs.com/higerzhang/p/4032051.html