LeetCode | 4Sum(四个数的和)

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)

题目解析:

类似3sum求解。用两个for循环,选取第一个和第二个,然后再用前后指针求解第三个和第四个数据。

class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        vector<int> sum;
        if(num.size() < 4)
            return res;
        sort(num.begin(),num.end());
        for(int i = 0;i < num.size()-3;i++){
            sum.push_back(num[i]);
            for(int j = i+1;j < num.size()-2;j++){
                sum.push_back(num[j]);
                int begin = j+1;
                int end = num.size()-1;
                while(begin < end){
                    if(num[i]+num[j]+num[begin]+num[end] == target){
                        sum.push_back(num[begin]);
                        sum.push_back(num[end]);
                        res.push_back(sum);
                        sum.pop_back();
                        sum.pop_back();
                        begin++;
                        while(begin < end && num[begin] == num[begin-1])
                            begin++;
                        end--;
                    }else if(num[i]+num[j]+num[begin]+num[end] < target)
                        begin++;
                    else
                        end--;
                }
                sum.pop_back();
                while(j < num.size()-2 && num[j] == num[j+1])
                    j++;
            }
            sum.pop_back();
            while(i < num.size()-3 && num[i] == num[i+1])
                i++;
        }
        return res;
    }
private:
    vector<vector<int> > res;
};

点赞