【answer】
Enumeration double loop [i..j] This section
also provides that will take nums [i] and nums [j]
then the next question now becomes labeled [i..j] This figure range which find two to make their numbers and target-nums [i] -nums [ j].
the complexity of the problem can be solved in O (N) is.
Complexity is therefore \ (O (N ^ 3)
\) of course also be written in meet-in-middle O (N ^ 2) is
stored as two and one, respectively, what number x (stored in the map which two of them subscript to).
Then go to double again in the map cycle and target-nums [i] -nums [ j] is the number pair.
Then merge.
Have the same landmarks are next removed (with a two digit);
[Code]
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int> > ans;
ans.clear();
vector<int> temp;
temp.resize(4);
sort(nums.begin(),nums.end());
int len = nums.size();
for (int i = 0;i < len;i++){
if (i>0 && nums[i]==nums[i-1]) continue;
for (int j = i+3;j<len;j++){
while(j+1<len && nums[j+1]==nums[j]) j++;
//在i..j这个范围内找和为target-nums[i]-nums[j]的数字
int key = target-nums[i]-nums[j];
int l = i+1,r = j-1;
while (l<r){
if (nums[l]+nums[r]>key){
r--;
}else if (nums[l]+nums[r]<key){
l++;
}else {
temp[0] = nums[i];temp[1] = nums[l];
temp[2] = nums[r];temp[3] = nums[j];
ans.push_back(temp);
while (l+1<r && nums[l+1]==nums[l]) l++;
while (r-1>l && nums[r-1]==nums[r]) r--;
l++;r--;
}
}
}
}
return ans;
}
};