题目:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:(-1, 0, 1) (-1, -1, 2)
分析:
(i)首先将序列从小到大排序,然后找出第一个非负数的位置nonnegPos,分成负数和非负数子序列
(ii)一个负数+两个非负数 -- 首先确定一个负数a,然后在非负数子序列中寻找2个数,其和为-a
(iii)一个非负数+两个负数 -- 同理调用twoSum()
(iii)三个零
bool isNonnegative(int i) { return (i >= 0); }
class Solution {
public:
void twoSum(vector<vector<int> > &ret, vector<int>::iterator beg, vector<int>::iterator end, int num)
{
vector<int> triplet(1, -num);
vector<int>::iterator e = end - 1;
for(vector<int>::iterator b = beg; b < end; b++)
{
if(b > beg && *b == *(b - 1)) continue;
while(b < e){
if(*b + *e== num){
triplet.push_back(*b); triplet.push_back(*e); sort(triplet.begin(), triplet.end());
ret.push_back(triplet); triplet.assign(1, -num);
break;
}
else if( e != end - 1 && *b + *e < num){ e++; break; }
e--;
}
}
}
vector<vector<int> > threeSum(vector<int> &num) {
vector<int>::iterator beg = num.begin(), end = num.end();
vector<vector<int> > ret; vector<int>::size_type ix;
sort(beg, end);
vector<int>::iterator nonnegPos = find_if(beg, end, isNonnegative);
for(ix = 0; ix < nonnegPos - beg; ix++){
if(ix > 0 && num[ix] == num[ix - 1]) continue;
twoSum(ret, nonnegPos, end, -num[ix]);
}
for(ix = nonnegPos - beg; ix < num.size(); ix++){
if(ix > nonnegPos - beg && num[ix] == num[ix - 1]) continue;
twoSum(ret, beg, nonnegPos, -num[ix]);
}
if(count(beg, end, 0) >= 3){
vector<int> zero(3, 0);
ret.push_back(zero);
}
return ret;
}
};