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]
]
利用3sum的思想,还是比较简单的
 1 class Solution {
 2 public:
 3     vector<vector<int>> fourSum(vector<int>& nums, int target) {
 4         sort(nums.begin(),nums.end());
 5         vector<int> temp;
 6         vector<vector<int>> res;
 7         //利用3sum
 8         int target3,target2;
 9         for(int i=0;i<nums.size();i++)
10         {
11             target3=target-nums[i];
12             for(int j=i+1;j<nums.size();j++)
13             {
14                 int front=j+1,back=nums.size()-1;
15                 target2=target3-nums[j];
16                 while(front<back)
17                 {
18                     if(nums[front]+nums[back]<target2)   front++;
19                     else if(nums[front]+nums[back]>target2)  back--;
20                     else
21                     {
22                          temp.push_back(nums[i]);
23                          temp.push_back(nums[j]);
24                          temp.push_back(nums[front]);
25                          temp.push_back(nums[back]);
26                          res.push_back(temp);
27                          while(nums[front]==temp[2])  front++;
28                          while(nums[back]==temp[3])  back--;
29                         temp.clear();
30                     }
31                 }
32                 while(j+1<nums.size()&&nums[j]==nums[j+1])   j++;
33             }
34             while(i+1<nums.size()&&nums[i]==nums[i+1])   i++;
35         }
36         return res;
37     }
38 };

 

posted on 2017-10-04 19:32  wsw_seu  阅读(121)  评论(0编辑  收藏  举报

导航