码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode(16. 4Sum)

时间:2016-03-28 23:32:29      阅读:364      评论: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.

给定一个数组,找出所有4个数的组合使得它们的和为target

思路:和3Sum,Two Sum都是类似的。主要是两个点:

1. 对数组排序,然后双指针分别从头尾遍历

2. 注意去重的问题

 1 class Solution {
 2 public:
 3     vector<vector<int>> fourSum(vector<int>& nums, int target) {
 4         int nsize = nums.size();
 5         sort(nums.begin(), nums.end());
 6         vector<vector<int>> result;
 7         for(int i = 0; i < nsize; i++){
 8             if(i != 0 && nums[i] == nums[i - 1])
 9                 continue;
10             for(int j = i + 1; j < nsize; j++){
11                 if(j != i + 1 && nums[j] == nums[j - 1])
12                     continue;
13                 int p = j + 1, q = nsize - 1;
14                 while(p < q){
15                     int sum = nums[i] + nums[j] + nums[p] + nums[q];
16                     if(sum < target){
17                         ++p;
18                         continue;
19                     }
20                     if(sum > target){
21                         --q;
22                         continue;
23                     }
24                    
25                         vector<int> tmp;
26                         tmp.push_back(nums[i]);
27                         tmp.push_back(nums[j]);
28                         tmp.push_back(nums[p]);
29                         tmp.push_back(nums[q]);
30                         result.push_back(tmp);
31                         
32                         while(++p < q && nums[p] == nums[p - 1]);
33                         while(p < --q && nums[q] == nums[q + 1]);
34                 }
35             }
36         }
37         return result;
38     }
39 };

 

LeetCode(16. 4Sum)

标签:

原文地址:http://www.cnblogs.com/coolqiyu/p/5330983.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!