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: 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] ]
这道题要求找出一个数组中所有和为0的三个数,而且组合不能重复,如[-1, -1, 2] 和 [-1, 2, -1] 就属于重复。
为了解决这道题,我们可以选择先固定一个数,然后遍历剩下两个数,对其求和,找出和的值等于固定数的相反数的组合即可。我们可以先对nums从小到大排序,然后依次固定nums[ i ],然后用两个指针j, k分别指向nums的头和尾,从两个方向向中间遍历,如果nums[i] + nums[j] + nums[k] = 0,则将此组合加入。为了除去重复的组合,我们可以利用set的特性,用set来保存组合。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
set<vector<int>> s;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++) {
if (nums[i] > 0) break;
int j = i + 1, k = nums.size() - 1;
int target = 0 - nums[i];
while (k > j) {
if (j < k && nums[j] + nums[k] == target) {
vector<int> temp;
temp.push_back(nums[i]);
temp.push_back(nums[j]);
temp.push_back(nums[k]);
cout << nums[i] << " " << nums[j] << " " << nums[k] << endl;
s.insert(temp);
while (j < k && nums[j] == nums[j + 1]) j++;
while (j < k && nums[k] == nums[k - 1]) k--;
j++;
k--;
} else if (nums[j] + nums[k] < target) j++;
else if (nums[j] + nums[k] > target) k--;
}
}
vector<vector<int>> v(s.begin(), s.end());
return v;
}
};