zoukankan      html  css  js  c++  java
  • 4Sum

    Question:

    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)

    Solution:
     1 class Solution {
     2 public:
     3     vector<vector<int>> fourSum(vector<int>& nums, int target) {
     4         vector< vector<int> > result;
     5     sort(nums.begin(),nums.end());
     6     if(nums.size()<4)
     7         return result;
     8     for(auto i=nums.begin();i!=nums.end()-3;i++)
     9     {
    10         for(auto j=i+1;j!=nums.end()-2;j++)
    11         {
    12             auto p=j+1;
    13             auto q=nums.end()-1;
    14             while(p<q)
    15             {
    16                 if(*i+*j+*p+*q<target)
    17                 {
    18                     p++;
    19                 }
    20                 else if(*i+*j+*p+*q>target)
    21                 {
    22                     q--;
    23                 }
    24                 else
    25                 {
    26                     vector<int> temp;
    27                     temp.push_back(*i);
    28                     temp.push_back(*j);
    29                     temp.push_back(*p);
    30                     temp.push_back(*q);
    31                     result.push_back(temp);
    32                     q--;
    33                 }
    34             }
    35         }
    36     }
    37     sort(result.begin(),result.end());
    38     auto it=unique(result.begin(),result.end());
    39     result.erase(it,result.end());
    40     return result;
    41         
    42     }
    43 };

    
    
  • 相关阅读:
    [Json.net]忽略不需要的字段
    [c#]exchange回复,全部回复,转发所遇到的问题
    [c#]获取exchange中的图片
    [c#基础]AutoResetEvent
    [C#基础]c#中的BeginInvoke和EndEndInvoke
    [CentOs7]安装mysql
    [CentOS7]安装mysql遇到的问题
    [CentOs7]图形界面
    [CentOS]添加删除用户
    在虚机中安装CentOS
  • 原文地址:https://www.cnblogs.com/riden/p/4631477.html
Copyright © 2011-2022 走看看