题目描述:
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] ]
本题要我们找到数组中所有3个数字相加为0的组合,而且不能有重复的。
解题思路:
因为给我们的数组是无序的,若是要找到所有组合就一定是要三层嵌套遍历的,所以要先进行排序。
排序完后的数组可以参照TowSum的解法:
将头一个数固定,在右端的数组中分别取最左和最右的数的下标为left和right。
当这两个数相加大于头一个数的负值时,右减,小于则反之。相当就加入二维数组,然后left加。
这道题比较头疼的是不能重复:
首先,如果头一个数重复的话可以直接跳过。
然后,若是后两个数重复的话可以和最后一次添加的三个数比较。因为这种解法各答案中的第一个数和第二个数都是升序,所以可以这么做。
代码:
1 class Solution { 2 public: 3 vector<vector<int>> threeSum(vector<int>& nums) { 4 vector<vector<int>> result; 5 int n = nums.size(); 6 if(n<3) 7 return result; 8 sort(nums.begin(), nums.end()); 9 for(int i=0; i<n-2; i++){ 10 if(i > 0 && nums[i] == nums[i-1]) 11 continue; 12 int left = i+1, right = n-1; 13 while(right>left){ 14 if(nums[left]+nums[right] == -nums[i]){ 15 if(result.size() > 0 && nums[right] == result[result.size()-1][2] && nums[left] == result[result.size()-1][1]) 16 left++; 17 else{ 18 vector<int> t = {nums[i], nums[left], nums[right]}; 19 result.push_back(t); 20 left++; 21 } 22 } 23 else if(nums[left]+nums[right] > -nums[i]) 24 right--; 25 else 26 left++; 27 } 28 } 29 return result; 30 } 31 };