标签:
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)
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> ret;
for(int i = 0;i < nums.size();i++)
{
int start = i+1;
int end = nums.size()-1;
if(i>0&&nums[i]==nums[i-1])//关键点1:去除已经重复的点
continue;
while(start<end)//转化为2sum问题
{
while(start>i+1&&nums[start]==nums[start-1])//关键点2:排除重复的部分
{
start++;
}
while(end<nums.size()-1&&nums[end]==nums[end+1])
{
end--;
}
int sum = nums[start]+nums[i]+nums[end];
if(start<end)
{
if(sum == 0)
{
vector<int> temp;
temp.push_back(nums[i]);
temp.push_back(nums[start]);
temp.push_back(nums[end]);
ret.push_back(temp);
start++;
}else if(sum>0)
{
end--;
}else{
start++;
}
}
}
}
return ret;
}
};
标签:
原文地址:http://blog.csdn.net/leosha/article/details/46679379