题目:
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:
思路分析:
代码:
#include <iostream> #include <vector> #include <string> vector<vector<int> > threeSum(vector<int> &num){ vector<vector<int> > ret; if(num.empty()) return ret; int size=num.size(); sort(num.begin(),num.end()); for(vector<int>::const_iterator it=num.begin();it!=num.end();it++){ if(it!=nu.begin() && *it==*(it-1)) continue; vector<int>::const_iterator front=it+1; vector<int>::const_iterator back=num.end()-1; while(front<back){ int sum=*it+*front+*back; if(sum>0){ back--; } else if(sum<0){ front++; } else if(front!=it+1 && *front==*(front-1)){ front++; } else if(back!=num.end() && *back==*(back+1)){ back--; } else{ vector<int> rsesult; result.push_back(*it); result.push_back(*front); result.push_back(*back); ret.push_back(result); front++; back--; } } } return ret; }
原文:http://www.cnblogs.com/sixue/p/4004533.html