思路:
- 类似3Sum,利用map存储可以省去判断重复数组,复杂度为 (O(n^4)),因为set判断元素是否重复也需要 (O(n)).
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
set<vector<int>> tmp;
int len = nums.size();
for(int i = 0; i < len - 3; i++) {
for(int j = i+1; j < len -2 ; j++){
int lo = j+1,hi = len-1;
while(lo < hi){
if(nums[i] + nums[j] + nums[hi] + nums[lo] == target){
tmp.insert({nums[i],nums[j],nums[lo],nums[hi]});
lo++;
hi--;
}else if(nums[i] + nums[j] + nums[hi] + nums[lo] < target){
lo++;
}else hi--;
}
}
}
for(auto m : tmp){
res.push_back(m);
}
return res;
}
};