Problem:
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)
个人解法:
- 对数组排序
- 确定四元数中的两个
- 遍历剩余数组确定两外两个
算法时间复杂度为O(n^3)。
网上看到一个时间复杂度O(n^2),空间复杂度为O(n)的解法:采用分治思想,先对数组预处理,求的元素两两之和,然后采用2Sum算法思想遍历数组求的四个数字之和。
class Solution { public: vector<vector<int> > fourSum(vector<int> &num, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function int nSize = num.size(); vector< vector<int> > result; if (nSize < 4) return result; sort(num.begin(), num.end()); vector<int> mid(4); set<string> isExit; for (int i = 0; i < nSize - 3; ++i) { mid[0] = num[i]; for (int j = i + 1; j < nSize - 2; ++j) { mid[1] = num[j]; int l = j + 1; int r = nSize - 1; int sum = target - num[i] - num[j]; while(l < r) { int tmp = num[l] + num[r]; if (sum == tmp) { string str; str += num[i]; str += num[j]; str += num[l]; str += num[r]; set<string>::iterator itr = isExit.find(str); if (itr == isExit.end()) { isExit.insert(str); mid[2] = num[l]; mid[3] = num[r]; result.push_back(mid); } ++l; --r; } else if(sum > tmp) ++l; else --r; } } } return result; } };