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: 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]
]

Solution:

Fix the first two numbers, and squeeze the last two numbers from left / right. 

 1 class Solution {
 2 public:
 3     vector<vector<int>> fourSum(vector<int>& nums, int target) {
 4         vector<vector<int> > result;
 5         if(nums.size() < 4) return result;
 6         
 7         sort(nums.begin(), nums.end());
 8         for(int i = 0; i <= nums.size() - 4; i++){
 9             if(i != 0 && nums[i] == nums[i - 1]) continue;
10            
11             for(int j = i + 1; j <= nums.size() - 3; j++){
12                 if(j != i + 1 && nums[j] == nums[j - 1]) continue;
13                 
14                 int left = j + 1, right = nums.size() - 1;
15                 while(left < right){
16                     int tempSum = nums[i] + nums[j] + nums[left] + nums[right];
17                 
18                     if(tempSum == target){
19                         if(left != j + 1 && nums[left] == nums[left - 1]) left++;
20                         else{
21                             vector<int> temp = {nums[i], nums[j], nums[left], nums[right]};
22                             result.push_back(temp);
23                             left++;
24                             right--;
25                         }
26                     }
27                     else if(tempSum > target) right--;
28                     else left++;
29                 }
30             }
31         }
32         return result;
33     }
34 };
原文地址:https://www.cnblogs.com/amazingzoe/p/5643259.html