题目描述:

Given an array S of n integers, are there elements a, b, c, 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]
]

解题思路:

用了和2Sum和3Sum一样的解题思路。

代码:

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

 

 

 

posted on 2018-02-24 19:43  宵夜在哪  阅读(84)  评论(0编辑  收藏  举报