思路:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution{
public:
vector<vector<int> > threeSum(vector<int>& nums){
vector<vector<int> > res;
std::sort(nums.begin(), nums.end());
for( int i = 0; i < nums.size(); i++){
int target = -nums[i];
int front = i+1;
int back = nums.size()-1;
while(front < back){
int sum = nums[front]+nums[back];
if(sum < target)
front++;
else if(sum > target)
back--;
else{
vector<int> triplet(3,0);
triplet[0] = nums[i];
triplet[1] = nums[front];
triplet[2] = nums[back];
res.push_back(triplet);
while(front <back && nums[front] == triplet[1]) front++;
while(front < back && nums[back] == triplet[2]) back--;
}
}
while(i + 1 < nums.size() && nums[i +1] == nums[i])
i++;
}
return res;
}
};
int main()
{
int a[] = {-1,0,1,2,-1,-4};
int len = sizeof(a) / sizeof(a[0]);
vector<int> nums(a, a+len);
Solution s;
vector<vector<int> > result;
result = s.threeSum(nums);
for(int q = 0; q < result.size(); q++) {
vector<int> x = result[q];
cout << "[";
int t;
for(t = 0; t < x.size()-1; t++) {
cout << x[t] << ",";
}
cout << x[t];
cout << "]" << endl;
}
return 0;
}