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)

思路:

类似
http://blog.csdn.net/lanxu_yy/article/details/11896109

代码:

class Solution {
public:
    vector<vector<int>>* v;
    vector<vector<int>> fourSum(vector<int> &num, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        v = new vector<vector<int>>();
        if(num.size() < 4)
        {
            return *v;
        }
        
        sort(num.begin(), num.end());
        
        for(int i = 0; i < num.size()-3; i++)
        {
            if(i > 0 && num[i] == num[i-1])
            {
                continue;
            }
            for(int j = i+1; j < num.size()-2; j++)
            {
                if(j > i+1 && num[j] == num[j-1])
                {
                    continue;
                }
                for(int k = j+1; k < num.size()-1; k++)
                {
                    if(k > j+1 && num[k] == num[k-1])
                    {
                        continue;
                    }
                    int left = k+1;
                    int right = num.size()-1;
                    while(left<=right)
                    {
                        int mid = left + ((right-left)>>1);
                        if(num[i] + num[j] + num[k] + num[mid] == target)
                        {
                            vector<int> tmp;
                            tmp.push_back(num[i]);
                            tmp.push_back(num[j]);
                            tmp.push_back(num[k]);
                            tmp.push_back(num[mid]);
                            
                            v->push_back(tmp);
                            break;
                        }
                        else if(num[i] + num[j] + num[k] + num[mid] > target)
                        {
                            right = mid - 1;
                        }
                        else
                        {
                            left = mid + 1;
                        }
                    }
                }
            }
        }
        
        return *v;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11897243
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞