title: Given An arrayS ofNintegers, is there elementsa, b, CinchSsuch thata + 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)
Translate: Give an array. Find a combination of 3 numbers equal to 0. Sorted in ascending order.
Idea: This question and the previous days brush two Sum principle is similar. It's just the opposite of the sum of the last number. Another problem is that if the current number and the next number repeat, you should exclude these duplicates, do not traverse, reduce complexity.
Code:
public static arraylist<arraylist<integer>> threesum (int[] num) {arraylist<arraylist<integer> > res = new arraylist<arraylist<integer>> (); if (num = = null| | NUM.LENGTH<3)//If there is only 2 digits or null return to the empty return res; Arrays.sort (num); for (int i = 0; i<num.length-2;i++)//guaranteed to have num.length-1 and num.length-2 two numbers in order to enter the loop {if (i > 0 && Amp Num[i] = = Num[i-1])//If there are repeated jumps directly. Continue Arraylist<arraylist<integer>> cur = twosum (num,i+1,-num[i]); Gets a subset of the number sequences that the current number can be combined. Res.addall (cur);} return res; } public static arraylist<arraylist<integer>>twosum (int []num,int start,int target) {arraylist& Lt arraylist<integer>> res = new arraylist<arraylist<integer>> (); if (num = = null| | Num.length < 2) return res; int L = start;//start position int pri = start-1;//current number int r = num.length-1;//terminating position while (L < R)//using clamp force, approaching target { if (num[l]+num[r] = = target)//{arraylist<integer> te = new ARRAylist<integer> ();//Match three numbers into the list te.add (Num[pri]); Te.add (Num[l]); Te.add (Num[r]); Res.add (TE); int k = L + 1;//removes duplicates from the next start of L. while (K < r&& num[k] = = Num[l]) k++; L = k; K = r-1;//removal of R's repetition while (K > L &&num[k] = = Num[r]) k--; R = k; } else if (Num[l] + num[r] > Target)//clamp Force r--; else l++; } return res; }If you ask for 4 sum, you can write a function to find out 3 sum and then in the integration into 4sum. The principle is actually similar.
A better approach is yet to be considered.
Leetcode 3Sum finds the sum of 3 numbers inside the array equal to the specified value.