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)
solution: method1: 类似于3sum的方法,大概是O(n^3)时间,感觉效率有点低;想了一下没想出更优化的解法,Google了下找到一个帖子总结了k-sum问题,链接如下:
http://tech-wonderland.net/blog/summary-of-ksum-problems.html 。 递归思考的话,确实k-sum问题的求解时间为O( n^(k-1) )。
method2: 还没想到,想到再更。
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
vector<vector<int> > res;
int size = num.size();
if(size < 4)
return res;
sort(num.begin(),num.end());
for(int fir = 0; fir < size - 3; fir++)
{
if(num[fir] == num[fir-1] && fir != 0)
continue;
for(int sec = fir +1; sec < size - 2; sec ++)
{
if(num[sec] == num[sec-1] && sec != fir+1)
continue;
int start = sec + 1;
int end = size - 1;
while(start < end)
{
int sum = num[fir] + num[sec] + num[start] + num[end];
if(sum == target)
{
vector<int>tuple(4,0);
tuple[0] = num[fir];
tuple[1] = num[sec];
tuple[2] = num[start];
tuple[3] = num[end];
res.push_back(tuple);
start++;
while(num[start] == num[start-1])
start++;
end--;
}
else if(sum < target)
{
start++;
}
else
{
end--;
}
}
}
}
return res;
}
};
实现中需注意去重。