leetcode132:4sum

题目描述

给出一个有n个元素的数组S,S中是否有元素a,b,c和d满足a+b+c+d=目标值?找出数组S中所有满足条件的四元组。
注意:
  1. 四元组(a、b、c、d)中的元素必须按非降序排列。(即a≤b≤c≤d)
  2. 解集中不能包含重复的四元组。
    例如:给出的数组 S = {1 0 -1 0 -2 2}, 目标值 = 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)↵

class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        vector <vector<int>> res;
        vector< int> temp (4,0);
        set<vector<int> > st;
        sort(num.begin(),num.end());
        int n=num.size();
        for (int i=0;i<n;i++){
            for (int j=i+1;j<n;j++){
                int left=j+1,right=n-1;
                while (left<right){
                    int sum=num[i]+num[j]+num[left]+num[right];
                    if (sum==target){
                        temp[0]=num[i];
                        temp[1]=num[j];
                        temp[2]=num[left];
                        temp[3]=num[right];
                        st.insert(temp);
                    }
                    if (sum<target)
                        left++;
                    else
                        right--;
                }
            }
        }
        set<vector<int>>::iterator it;
        for (it=st.begin();it !=st.end();it++)
            res.push_back(*it);
        return res;
    }
};
posted on 2020-08-01 10:33  滚雪球效应  阅读(123)  评论(0编辑  收藏  举报