[leetcode] 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)

即给定一个数组S,输出S中的四个元素使得之和为0,且每个元组中元素从小到大的排列,且不重不漏。

解法和3Sum类似,使用四个指针i,j,p,q来遍历数组。其中pq分别从首和尾开始。注意判重方法与3Sum相同。

代码如下:

 1 class Solution {

 2     public:

 3          vector<vector<int> > fourSum(vector<int> &num, int target) {

 4             vector<vector<int> > res;

 5             if( num.size() < 4 )

 6             {

 7                 return res;

 8             }

 9             vector<int> arr = num;

10             sort(arr.begin(), arr.end());

11             for( int i = 0 ; i < arr.size()-3 ; i++ )

12             {

13                 if(i > 0 && arr[i] == arr[i-1])

14                   continue;

15                 for( int j = i+1 ; j < arr.size()-2 ; j++ )

16                 {

17                     if(j > i+1 && arr[j] == arr[j-1])

18                       continue;

19                     int p = j+1;

20                     int q = arr.size()-1;

21                     while(p < q)

22                     {

23                         if (p > j + 1 && arr[p] == arr[p-1])

24                         {

25                             p++;

26                             continue;

27                         }

28                         if (q < arr.size() - 1 && arr[q] == arr[q+1])

29                         {

30                             q--;

31                             continue;

32                         }

33                         int sumtmp  = arr[i] + arr[j] + arr[p] + arr[q] ;

34                         if (sumtmp == target)

35                         {

36                             vector<int> tmp;

37                             tmp.push_back(arr[i]);

38                             tmp.push_back(arr[j]);

39                             tmp.push_back(arr[p]);

40                             tmp.push_back(arr[q]);

41                             res.push_back(tmp);

42                             p++;

43                         }

44                         else if( sumtmp < target )

45                         {

46                             p++;

47                         }

48                         else

49                         {

50                             q--;

51                         }

52                     }

53                 }

54 

55             }

56             return res;

57         }

58 };

 

你可能感兴趣的:(LeetCode)