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;
        }
    };


查看全文
  • 相关阅读:
    修改maven远程仓库为阿里的maven仓库(复制)
    Vue下iframe如何实现和父窗口的通信
    Vue在子组件内如何触发父组件的方法
    PhpStorm环境设置Debug
    史上最全的Excel数据编辑处理技巧(转)
    按钮样式
    字符和数字对齐的字体
    使用jquery控制只能输入数字,并且关闭输入法(转)
    Javascript中字符串转换成Date的方法
    MongoDB工具MagicMongoDBTool
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10497594.html
  • Copyright © 2011-2022 走看看