题目:
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:
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)
先对数组排序,利用STL set 解决了重复 quadruplet 问题, 再把4sum分解为 1个元素+3Sum,再进一步分解为 1个元素 + 另1个元素 + 2Sum,再利用2Sum求解。336ms过。
class Solution { public: vector<vector<int>> fourSum(vector<int> &num, int target) { vector<vector<int>> results; if(num.size() < 4) return results; sort(num.begin(), num.end()); set<vector<int>> result; for(int i = 0; i < num.size() - 3; i++) { int sum = target - num[i]; for(int j = i + 1; j < num.size() - 2; j++) { sum -= num[j]; //2-sum here int start = j + 1; int end = num.size() - 1; while(start < end) { if(num[start] + num[end] == sum) { vector<int> temp; temp.push_back(num[i]); temp.push_back(num[j]); temp.push_back(num[start]); temp.push_back(num[end]); result.insert(temp); start++; end--; } else if(num[start] + num[end] < sum) start++; else end--; } sum += num[j]; } } for(auto iter: result) { results.push_back(iter); } return results; } };