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)
4sum转为3sum,3sum转为2sum,代码如下:
1 class Solution {
2 public:
3 vector<vector<int> > fourSum(vector<int> &num, int target) {
4 sort(num.begin(), num.end()); //需要对数组元素进行排序
5 vector< vector<int> > ans;
6 for(int i=0; i+4<=num.size(); ++i) {
7 if( i>0 && num[i] == num[i-1] ) continue;
8 vector< vector<int> > threesum = threeSum(num, i+1, target-num[i]);
9 for(int j=0; j<threesum.size(); ++j) {
10 threesum[j].insert(threesum[j].begin(), num[i]); //non-descending order
11 ans.push_back(threesum[j]);
12 }
13 }
14 return ans;
15 }
16
17 vector<vector<int> > threeSum(vector<int> &num, int left, int target) {
18 vector< vector<int> > ans;
19 for(int i=left; i+3<=num.size(); ++i) {
20 if( i>left && num[i] == num[i-1] ) continue; //如果该数和前面数相同,那么需要直接跳过
21 vector< vector<int> > twoans = twoSum(num, i+1, num.size()-1, target-num[i]); //直接转为twosum问题
22 for(int j=0; j<twoans.size(); ++j) {
23 twoans[j].insert(twoans[j].begin(), num[i]); //non-descending order
24 ans.push_back(twoans[j]);
25 }
26 }
27 return ans;
28 }
29
30 vector< vector<int> > twoSum(vector<int>& num, int left, int right, int target) {
31 vector< vector<int> > ans;
32 vector<int> v;
33 while( left < right ) {
34 int sum = num[left] + num[right];
35 if( sum == target ) { //找到一个解
36 v.push_back(num[left]);
37 v.push_back(num[right]);
38 ans.push_back(v);
39 v.clear();
40 ++left; //left要后移至不同于前一个数位置上
41 while( left < right && num[left] == num[left-1] ) ++left;
42 --right; //right要前移至不同于后一个数位置上
43 while( left < right && num[right] == num[right+1] ) --right;
44 }
45 else if( sum > target ) --right;
46 else ++left;
47 }
48 return ans;
49 }
50 };