每日算法之十六: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)
直接上代码:

最主要的还是进行去重。

<span style="font-size:18px;">class Solution {
  public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
         vector<vector<int> > ret;
        if(num.size()==0) return ret;
        sort(num.begin(),num.end());
        for(int i = 0;i<num.size();++i)
        {
            if(i>0&&num[i] == num[i-1])
                continue;
            for(int j = i+1;j<num.size();j++)
            {
                if(j>i+1&&num[j] == num[j-1])
                    continue;
                int k = j+1,t = num.size()-1;
                while(k<t)
                {
                    if(k>j+1&&num[k] == num[k-1])//这里是if,而不是while.如果是while可能会越界,在每一次
                        {k++;continue;}     //指针变化之后都要进行判断。避免越界的发生。</span><pre name="code" class="cpp"><span style="font-size:18px;">               //这里是contimue,而不是break.如果是while,也不能是break,因为可能导致t指针的重复。</span>
if(t<num.size()-1&&num[t] == num[t+1]) {t--;continue;} // int sum = num[i]+num[j]+num[k]+num[t]; if(sum<target) k++; else if(sum>target) t--; else { vector<int> v; v.push_back(num[i]); v.push_back(num[j]); v.push_back(num[k]); v.push_back(num[t]); ret.push_back(v); k++;//哪一个变化都可以 } } } } return ret; }};

 
 





你可能感兴趣的:(4sum)