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:
- 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.
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) 分析: 没什么好说的,关键是得想到这样做。 代码: class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>> v1; sort(nums.begin(),nums.end()); int len=nums.size(); for(int i=0;i<(len-3);++i) { if((nums[i+1]>0) &&(nums[i]>target)) break; if((i>0)&&(nums[i]==nums[i-1])) continue; for(int j=i+1;j<(len-2);++j) { if((j>i+1) && (nums[j]==nums[j-1])) continue; int t1=nums[i]+nums[j]; if((t1>target)&&(nums[j]>0)) break; int l=j+1; int r=len-1; while(l<r) { int t2=nums[l]+nums[r]; if(t2<(target-t1)) ++l; else if(t2>(target-t1)) --r; else { vector<int> v2{nums[i],nums[j],nums[l],nums[r]}; v1.push_back(v2); ++l;--r; while(l<r &&nums[l]==nums[l-1]) ++l; while(l<r &&nums[r]==nums[r+1]) --r; } } } } return v1; } };