zoukankan      html  css  js  c++  java
  • leetcode[18]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)
    class Solution {
    public:
        vector<vector<int>> fourSum(vector<int> &num, int target) {
            vector<vector<int>> res;
            if(num.size()<4)return res;
            sort(num.begin(),num.end());
            int c,d;
            for(int a=0;a<num.size();a++)
            {
                if(a>0&&num[a]==num[a-1])
                continue;
                for(int b=a+1;b<num.size();b++)
                {
                    if(b>a+1&&num[b]==num[b-1])
                    continue;
                    c=b+1;
                    d=num.size()-1;
                    while(c<d)
                    {
                        if(c>b+1&&num[c]==num[c-1])
                        {
                            c++;
                            continue;
                        }
                        if(d<num.size()-1&&num[d]==num[d+1])
                        {
                            d--;
                            continue;
                        }
                        int sum=num[a]+num[b]+num[c]+num[d];
                        if(sum<target)c++;
                        else if(sum>target)d--;
                        else
                        {
                            vector<int> temp;
                            temp.push_back(num[a]);
                            temp.push_back(num[b]);
                            temp.push_back(num[c]);
                            temp.push_back(num[d]);
                            res.push_back(temp);
                            c++;
                            d--;
                        }
                    }
                }
            }
            return res;
        }
    };
  • 相关阅读:
    hdu4665 DFS
    hdu4665 DFS
    hdu4717 三分(散点的移动)
    POJ 2559 Largest Rectangle in a Histogram(单调栈) && 单调栈
    洛谷 P2347 砝码称重
    洛谷 P3009 [USACO11JAN]利润Profits
    洛谷 P2925 [USACO08DEC]干草出售Hay For Sale
    洛谷 P1616 疯狂的采药
    洛谷 P1086 花生采摘
    洛谷 P1048 采药
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4283673.html
Copyright © 2011-2022 走看看