LeetCode(16. 4Sum)

Posted 记性不好,多记记吧

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(16. 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.

给定一个数组,找出所有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)的主要内容,如果未能解决你的问题,请参考以下文章

4Sum -- LeetCode

[Leetcode] 4Sum

leetcode 18 4Sum

LeetCode——18. 4Sum

LeetCode - 18. 4Sum

Leetcode018 4Sum