每日算法之十六:4sum

2014-11-24 13:28:36 · 作者: · 浏览: 33

Given an array S of n integers, are there elements a, b, c, 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
         
           > fourSum(vector
          
            &num, int target) { vector
           
             > ret; if(num.size()==0) return ret; sort(num.begin(),num.end()); for(int i = 0;i
            
             0&&num[i] == num[i-1]) continue; for(int j = i+1;j
             
              i+1&&num[j] == num[j-1]) continue; int k = j+1,t = num.size()-1; while(k
              
               j+1&&num[k] == num[k-1])//这里是if,而不是while.如果是while可能会越界,在每一次 {k++;continue;} //指针变化之后都要进行判断。避免越界的发生。
              
             
            
           
          
         
                   //这里是contimue,而不是break.如果是while,也不能是break,因为可能导致t指针的重复。
    if(t target) t--; else { vector 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; }};