zoukankan      html  css  js  c++  java
  • LeetCode 017 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)

    【题意】

        给定一个数组,从中取4个数使它们的和等于target, 找出全部的组合。
        不能有反复;
        且组合中各个数升序排列。


    【思路】

        思路和3Sum的思路全然同样,先确定第一个数,剩下的就又变成3Sum问题了


    【代码】

    class Solution {
    public:
        vector<vector<int> > fourSum(vector<int> &num, int target) {
            vector<vector<int> >result;
            int size=num.size();
            if(size<4)return result;
            sort(num.begin(), num.end());       //排序
            for(int p1=0; p1<size-3; p1++){
                if(p1!=0&&num[p1]==num[p1-1])continue;  //第一个数排重
                for(int p2=p1+1; p2<size-2; p2++){
                    if(p2!=p1+1 && num[p2]==num[p2-1])continue; //第二个数排重
                    int p3=p2+1;
                    int p4=size-1;
                    while(p3<p4){
                        if(p3!=p2+1 && num[p3]==num[p3-1]){p3++;continue;}  //第三个数排重
                        int sum=num[p1]+num[p2]+num[p3]+num[p4];
                        if(sum==target){
                            vector<int> quadruplet;
                            quadruplet.push_back(num[p1]);
                            quadruplet.push_back(num[p2]);
                            quadruplet.push_back(num[p3]);
                            quadruplet.push_back(num[p4]);
                            result.push_back(quadruplet);
                            p3++;p4--;
                        }
                        else if(sum>target)p4--;
                        else p3++;
                    }
                }
            }
            return result;
        }
    };


查看全文
  • 相关阅读:
    Selenium2Library系列 keywords 之 _SelectElementKeywords 之 _get_labels_for_options(self, options)
    Selenium2Library系列 keywords 之 _SelectElementKeywords 之_get_select_list_options(self, select_list_or_locator)
    Selenium2Library系列 keywords 之 _SelectElementKeywords 之_get_select_list(self, locator)
    Selenium2Library中的Get Alert Message
    selenium+testNG+Ant
    Maven安装testNG
    在FOR中使用close window,循环次数大于1就会报异常
    时间格式去‘0’
    序列化和反序列化组件 基表的使用 多表断关联关系分析 多表序列化组件 自定义子序列化深度连表 多表反序列化 序列化与反序列化整合 群增接口实现 单删群删接口实现 单整体改 单与群局部改
    drf安装与封装风格 drf请求生命周期 drf五大模块(请求模块,渲染模块,解析模块,异常处理模块,响应模块)
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10497594.html
  • Copyright © 2011-2022 走看看