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:
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
给定一个数组,找出和为0的左右三数组合
两点注意:1. 不能有重复组合
2. 组合中的三个数要升序排列
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> >result;
int size=num.size();
if(size<3)return result; //判断数组长度是否大于3
sort(num.begin(), num.end()); //排序
for(int p1=0; p1<size-2; p1++){
if(p1!=0 && num[p1]==num[p1-1])continue; //第一位排重
int p2=p1+1;
int p3=size-1;
while(p2<p3){
if(p2!=p1+1 && num[p2]==num[p2-1]){p2++; continue;} //第二位排重
int sum=num[p1]+num[p2]+num[p3];
if(sum==0){
vector<int> triplet;
triplet.push_back(num[p1]);
triplet.push_back(num[p2]);
triplet.push_back(num[p3]);
result.push_back(triplet);
p2++;p3--;
}
else if(sum>0)p3--;
else p2++;
}
}
return result;
}
};LeetCode 015 3Sum,布布扣,bubuko.com
原文地址:http://blog.csdn.net/harryhuang1990/article/details/25960109