Given an array S of n integers, is 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:
Elements in a triplet (A,B,C) must is in non-descending order. (ie, a≤b≤c)
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)
Analysis: According to test instructions, we can find a collection of three numbers equal to 0, so we use two-dimensional array storage.
First extract a variable, the variable from left to right recursive traversal, recursive at the same time set two variables, let it a from the right side of the first variable, one from the end of the array, synchronous to the middle, a bit similar to the quick sort of judging way,
- If the sum of the three numbers is less than 0, the second variable is added as a bonus;
- If the sum of three numbers is greater than 0, the third variable is reduced by itself;
- If three numbers are added equal to zero, then three numbers are added to the array, and then the second variable and the third variable are synchronized to increase or decrease, and to determine whether there are duplicate numbers in the process of self-increment;
Recursively until the condition of the first variable expires.
Code (c + +):
classSolution { Public: vector<vector<int> >Threesum ( vector<int>&nums) { vector<vector<int> >Result Sort (Nums.begin (), Nums.end ()); for(inti =0; I < nums.size (); i++) {if(I >0&& Nums[i] = = nums[i-1])Continue; Threenumber (nums, result, i); }returnResult }//return vector<vector<int> > Results voidThreenumber ( vector<int>&nums, vector<vector<int> >&results,intCurindex) {inti = Curindex +1;intj = nums.size ()-1; while(I < J) {if(Nums[curindex] + nums[i] + Nums[j] <0) i++;Else if(Nums[curindex] + nums[i] + nums[j] >0) j--;Else{ vector<int>V V.push_back (Nums[curindex]); V.push_back (Nums[i]); V.push_back (Nums[j]); Results.push_back (v); i++; j--; while(I < J && Nums[i]==nums[i-1]) i++; while(J > I && nums[j] = = Nums[j +1]) j--; } } }};
Leetcode[15]-3sum