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)
和2Sum,3Sum的思路基本上一样,这类问题都是先排序,然后由K Sum转换成K-1 Sum,
比如4Sum先选一个,然后从剩下的数字中求3Sum
所以问题最后还是时间复杂度的估算问题,K Sum的暴力求解是O(n ^ K)的复杂度,据说有证明最好的优化为n(n ^ k -1)所以放心大胆的一遍遍搜。。
AC代码:
class Solution { public: vector<vector<int> > fourSum(vector<int> &num, int target) { sort(num.begin(), num.end()); vector<vector<int>> ans; if(num.size() < 4){ return ans; } for(int i = 0; i < num.size() - 3; ++i){ if(i == 0 || num[i] != num[i - 1]){ for(int j = i + 1; j < num.size() - 2; ++j){ if(j == i + 1 || num[j] != num[j - 1]){ int left = j + 1; int right = num.size() - 1; int CTarget = target - num[i] - num[j]; while(left < right){ if(num[left] + num[right] < CTarget){ while(left < right && num[left] == num[(left++) + 1]){ //去除重复元素,并且保证left至少会+1,除非left >= right ; } }else if(num[left] + num[right] > CTarget){ while(left < right && num[right] == num[(right--) - 1]){ ; } }else{ vector<int> temp = {num[i], num[j], num[left], num[right]}; ans.push_back(temp); while(left < right && num[right] == num[(right--) - 1]){ ; } while(left < right && num[left] == num[(left++) + 1]){ ; } } } } } } } return ans; } };
时间: 2024-10-23 14:18:44