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)

思路:
类似前3题,不过在外层是两层循环。要注意判断重复的情况。
代码:
 1     vector<vector<int> > fourSum(vector<int> &num, int target) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         vector<vector<int> > result;
 5         vector<int> tmp;
 6         result.clear();
 7         tmp.clear();
 8         int i,j,k,t;
 9         int len = num.size();
10         if(len < 4)
11             return result;
12         sort(num.begin(), num.end());
13         for(i = 0; i < len-3; i++){
14             while(i > 0 && num[i] == num[i-1])
15                 i++;
16             for(j = i+1; j < len-2; j++){
17                 while(j > i+1 && num[j] == num[j-1])
18                     j++;                    
19                 k = j+1;
20                 t = len-1;
21                 while(k<t){
22                     while(k > j+1 && num[k] == num[k-1])
23                         k++;
24                     while(t < len-1 && num[t] == num[t+1])
25                         t--;
26                     if(k>=t)
27                         break;
28                     int total = num[i] + num[j] + num[k] + num[t];
29                     if(total < target)
30                         k++;
31                     else if(total > target)
32                         t--;
33                     else{
34                         tmp.push_back(num[i]);
35                         tmp.push_back(num[j]);
36                         tmp.push_back(num[k]);
37                         tmp.push_back(num[t]);
38                         result.push_back(tmp);
39                         tmp.clear();
40                         k++;
41                         t--;
42                     }
43                 }
44             }
45         }
46         return result;
47     }

 

posted on 2013-11-07 21:45  waruzhi  阅读(164)  评论(0编辑  收藏  举报

导航