zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    弹弹弹,走到哪里弹到哪里 —— 关于上海电信强制弹窗广告
    对Live Writer支持的继续改进:设置随笔地址别名(EntryName)
    【公告】6月20日0:00~1:00(今天夜里)机房网络设备调整
    上周热点回顾(6.46.10)
    [功能改进]Live Writer发博支持“建分类、加标签、写摘要”
    上周热点回顾(6.186.24)
    上周热点回顾(6.116.17)
    [转].NET 绘制 EAN13 (商品条码)
    [转]C#连接操作mysql实例
    [转]MySQLHelper类
  • 原文地址:https://www.cnblogs.com/hrnn/p/13413616.html
Copyright © 2011-2022 走看看