【leetcode】4Sum

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)

 

与3Sum类似,只是我们现在需要遍历两个元素,a,b,然后在利用两个指针的方法求c,d
 
 1 class Solution {
 2 public:
 3     vector<vector<int> > fourSum(vector<int> &num, int target) {
 4        
 5         int n=num.size();
 6         int i,j,k,l;
 7         int a,b,c,d;
 8         sort(num.begin(),num.end());
 9         vector<vector<int> > result;
10         for(int i=0;i<n-3;i++)
11         {
12             for(int j=i+1;j<n-2;j++)
13             {
14                 k=j+1;
15                 l=n-1;
16  
17                 while(k<l)
18                 {
19                     a=num[i];
20                     if(i>0&&num[i]==num[i-1])
21                     {
22                         break;
23                     }
24                    
25                     b=num[j];
26                     if(j>i+1&&num[j]==num[j-1])
27                     {
28                         break;
29                     }
30                    
31                     c=num[k];
32                     if(k>j+1&&num[k]==num[k-1])
33                     {
34                         k++;
35                         continue;
36                     }
37                    
38                     d=num[l];
39                     if(l<n-1&&num[l]==num[l+1])
40                     {
41                         l--;
42                         continue;
43                     }
44                    
45                     int sum=a+b+c+d;
46                    
47                     if(sum<target)
48                     {
49                         k++;
50                     }
51                     else if(sum>target)
52                     {
53                         l--;
54                     }
55                     else
56                     {
57                         vector<int> tmp(4);
58                         tmp[0]=a;
59                         tmp[1]=b;
60                         tmp[2]=c;
61                         tmp[3]=d;
62                         result.push_back(tmp);
63                         k++;
64                         l--;
65                     }
66                 }
67             }
68         }
69         return result;
70     }
71 };

 

posted @ 2014-12-28 20:03  H5开发技术  阅读(161)  评论(0编辑  收藏  举报