4Sum
Jan 27 '12
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)
方法1:利用和3Sum一样的思路,但是复杂度为O(N^3),偷懒用之前的代码,堆在一起看起来就很屎,懒得改了。
代码:
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
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(num.begin(),num.end());
vector<vector<int>> ret4;
set<vector<int>> set4;
//visit each positive number as target and use 2Sum to the left ones
int target3;
vector<int>::iterator it = num.begin();
for(;it!=num.end();){
if(it!=num.begin() && *it == *(it-1)) {
it++;
continue;
}
target3 =target-*it;
//erase the element
it = num.erase(it);
//3Sum
set<vector<int>> set3 = threeSum(num,target3,target-target3);
set4.insert(set3.begin(),set3.end());
//insert the element
it = num.insert(it,target-target3);
it++;
}
ret4.insert(ret4.end(),set4.begin(),set4.end());
return ret4;
}set<vector<int> > threeSum(vector<int> &num,int target3,int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int>> ret3;
//visit each positive number as target and use 2Sum to the left ones
int target2;
set<vector<int>> set3;
vector<int>::iterator it = num.begin();
for(;it!=num.end();){
if(it!=num.begin() && *it == *(it-1)) {
it++;
continue;
}
target2 = target3 -*it;
//erase the element
it = num.erase(it);
//2Sum2
set<vector<int>> set2 = twoSum2(num,target2,target3,target);
set3.insert(set2.begin(),set2.end());
//insert the element
it = num.insert(it,target3-target2);
it++;
}
return set3;
} set<vector<int>> twoSum2(vector<int> &numbers, int target2,int target3,int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//match
int i = 0;
int j = numbers.size()-1;
set<vector<int>> ret2;
while(i<j){
if(numbers[i]+numbers[j]==target2){
vector<int> ret;
ret.push_back(numbers[i]);
ret.push_back(numbers[j]);
ret.push_back(target3-target2);
ret.push_back(target);
sort(ret.begin(),ret.end());
ret2.insert(ret);
i++;
j--;
}else if(numbers[i]+numbers[j]>target2){
j--;
}else{
i++;
}
}
return ret2;
}
};
时间:1800 milli secs
方法2: 对num生成两两的数对,然后对数对间进行2Sum,这样空间复杂度为O(N^2),时间复杂度也为O(N^2)。
代码改天补上