• 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)
    

     C++代码实现:

    #include<iostream>
    #include<algorithm>
    #include<vector>
    using namespace std;
    
    class Solution
    {
    public:
        vector<vector<int> > fourSum(vector<int> &num,int target)
        {
            if(num.empty())
                return vector<vector<int> >();
            sort(num.begin(),num.end());
            vector<vector<int> > ret;
            int n=num.size();
            int i,j;
            for(i=0; i<n-3; i++)
            {
                //只保留第一个不重复的,其余的都删了,因为left会选择重复的
                if(i>=1&&num[i]==num[i-1])
                    continue;
                for(j=n-1; j>i+2; j--)
                {
                    //只保留最后一个不重复的,其余的都删了,因为right会选择重复的
                    if(j<n-1&&num[j+1]==num[j])
                       continue;
                    int left=i+1;
                    int right=j-1;
                    vector<int> tmp;
                    while(left<right)
                    {
                        //只保留最后一个不重复的,其余的都删了,因为left会选择重复的
                        if(right<j-1&&num[right]==num[right+1])
                            right--;
                        else if(num[i]+num[j]+num[left]+num[right]==target)
                        {
                            tmp= {num[i],num[left],num[right],num[j]};
                            ret.push_back(tmp);
                            left++;
                            right--;
                        }
                        else if(num[i]+num[j]+num[left]+num[right]<target)
                            left++;
                        else if(num[i]+num[j]+num[left]+num[right]>target)
                            right--;
                    }
                }
            }
            return ret;
        }
    };
    int main()
    {
        vector<int> vec= {-5,5,4,-3,0,0,4,-2};
        Solution s;
        vector<vector<int> > result=s.fourSum(vec,4);
        for(auto a:result)
        {
            for(auto v:a)
                cout<<v<<" ";
            cout<<endl;
        }
        cout<<endl;
    }

    注意处理重复的vector。。。。

     
  • 相关阅读:
    placeholder在ie浏览器里不显示的问题解决
    条件注释判断浏览器版本<!--[if lt IE 9]>
    在CSS中,BOX的Padding属性的数值赋予顺序为
    PhpStorm的注册码、Key
    关于【bootstrap modal 模态框弹出瞬间消失的问题】
    python 常见算法
    scrapy 爬虫基础
    python中的小知识点
    python 数据结构简介
    前端插件定制--表头和表内容
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4120872.html
Copyright © 2020-2023  润新知