题目:
解答:
参考:
http://tech-wonderland.net/blog/summary-of-ksum-problems.html
http://blog.csdn.net/v_july_v/article/details/6419466
http://www.cnblogs.com/TenosDoIt/p/3649607.html
代码:
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > res;
sort(num.begin(), num.end());
for(int i = 0; i < num.size(); i++)
{
if (i > 0 && num[i] == num[i - 1])
continue;
int j = 0;
int k = num.size() - 1;
while (j < k)
{
if (j == i)
{
++j;
continue;
}
if (k == i)
{
--k;
continue;
}
if (num[j] + num[k] == -num[i])
{
vector<int> temp;
if (i < j)
{
temp.push_back(num[i]);
temp.push_back(num[j]);
temp.push_back(num[k]);
}
else if (i < k)
{
temp.push_back(num[j]);
temp.push_back(num[i]);
temp.push_back(num[k]);
}
else
{
temp.push_back(num[j]);
temp.push_back(num[k]);
temp.push_back(num[i]);
}
if (find(res.begin(), res.end(), temp) == res.end())
res.push_back(temp);
++j;
--k;
}
else if (num[j] + num[k] < -num[i])
++j;
else
--k;
}
}
return res;
}
};