首页 > 其他 > 详细

[Leetcode] 4Sum

时间:2014-04-27 20:54:10      阅读:444      评论:0      收藏:0      [点我收藏+]

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一样,先用两层循环,注意去重。

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     vector<vector<int> > fourSum(vector<int> &num, int target) {
 4         vector<vector<int> > res;
 5         vector<int> v(4);
 6         int sum;
 7         if (num.size() < 4) return res;
 8         sort(num.begin(), num.end());
 9         for (int i = 0; i < num.size() - 3; ++i) {
10             if (i > 0 && num[i] == num[i-1]) 
11                 continue;
12             for (int j = i + 1; j < num.size() - 2; ++j) {
13                 if (j > i + 1 && num[j] == num[j-1])
14                     continue;
15                 int low = j + 1, high = num.size() - 1;
16                 while (low < high) {
17                     sum = num[i] + num[j] + num[low] + num[high];
18                     if (sum > target) {
19                         --high;
20                     } else if (sum < target) {
21                         ++low;
22                     } else {
23                         v[0] = num[i];
24                         v[1] = num[j];
25                         v[2] = num[low];
26                         v[3] = num[high];
27                         res.push_back(v);
28                         while (low < num.size() && num[low+1] == num[low]) ++low;
29                         while (high > 0 && num[high-1] == num[high]) --high;
30                         ++low; --high;
31                     }
32                 }
33             }
34         }
35         return res;
36     }
37 };
bubuko.com,布布扣

 

 

[Leetcode] 4Sum,布布扣,bubuko.com

[Leetcode] 4Sum

原文:http://www.cnblogs.com/easonliu/p/3694667.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!