The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0. A solution set is: (-1, 0, 0, 1) (-2, -1, 1, 2) (-2, 0, 0, 2)
Question:Given an array S that contains n integers, whether the elements a, B, c, and d exist in array s make a + B + c + d = target. find all such combinations in array S.
Note:
1. These four elements must be in ascending order (ie, a ≤ B ≤ c ≤ d)
2. Duplicate solutions are not included in the final result.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0. A solution set is: (-1, 0, 0, 1) (-2, -1, 1, 2) (-2, 0, 0, 2)
Algorithm analysis:* Using the title "3Sum" code https://leetcode.com/problems/3sum/
* First, sort the array in ascending order, and then traverse the 3Sum algorithm from the first element. The target value is (target-nums [I]), and The traversal array is the array after the element.
* In this way, the elements in the final arraylist can be sorted in ascending order and will not be duplicated, because each time we start with this, the elements to be traversed are the smallest elements in the array.
AC code:
Public class Solution {private static ArrayList> ret = new ArrayList> (); public ArrayList> fourSum (int [] nums, int target) {int newtarget = 0; arrayList> finalres = new ArrayList> (); Arrays. sort (nums); for (int I = 0; I <nums. length; I ++) {ArrayList> temlist = new ArrayList> (); if (I> 0 & nums [I] = nums [I-1]) continue; // avoid repeated results. The result is skipped directly after the result is equal to the result. Newtarget = target-nums [I]; int inputnums [] = new int [nums. length-i-1]; for (int ii = 0; ii
> ThreeSum (int [] num, int newtarget, int firstnum) {if (num = null | num. length <3) return ret; Arrays. sort (num); int len = num. length; for (int I = 0; I <len-2; I ++) {if (I> 0 & num [I] = num [I-1]) continue; // avoid repeated results. The result is skipped directly after the result is equal to the result. Find (num, I + 1, len-1, num [I], newtarget, firstnum); // find the sum of two numbers and num [I] 0} return ret ;} public static void find (int [] num, int begin, int end, int target, int newtarget, int firstnum) {int l = begin, r = end; while (l <r) {if (num [l] + num [r] + target = newtarget) {ArrayList
Ans = new ArrayList
(); Ans. add (firstnum); // different from the original 3Sum algorithm, remember to add each revelation traversal element to the smallest of the four ans. add (target); ans. add (num [l]); ans. add (num [r]); ret. add (ans); // put in the result set while (l <r & num [l] = num [l + 1]) l ++; // avoid duplicate results, the latter is directly skipped if it is equal to the latter. While (l <r & num [r] = num [r-1]) r --; // avoid repeated results, and the subsequent parts that are equal to it are skipped directly. L ++; r --;} else if (num [l] + num [r] + target <newtarget) l ++; else r --;}}}