Problem Description:
Given an array S of n integers, is there elements a, b, C, and D in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
- Elements in a quadruplet (a,b,c,D) must is in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- 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)
Problem Solving Ideas:
Similar to the previous 3sum, except that there is a set of loops outside, with a time complexity of O (n^3)
The code is as follows:
public class Solution {list<list<integer>> ans = new arraylist<list<integer>> ();p ublic List< ; List<integer>> foursum (int[] nums, int target) {int length = Nums.length;int tmp;if (nums = NULL | | Length < 4) return ans; Arrays.sort (Nums); for (int i = 0; i < length-3, i++) {if (i > 0 && nums[i] = = Nums[i-1]) continue;for (in T j = i + 1; J < Length-2; J + +) {if (J > i + 1 && nums[j] = = nums[j-1]) Continue;int begin = j + 1;int end = Length-1;while (Begin < End) {tmp = Nums[begin] + nums[end] + nums[i] + nums[j];if (tmp = = target) {list<integer> List = new Arraylist<i Nteger> (); List.add (Nums[i]); List.add (Nums[j]); List.add (Nums[begin]); List.add (Nums[end]); Ans.add (list); while (Begin < End && Nums[begin + 1] = = Nums[begin]) begin++;begin++;while (Begin < End && Nums[end-1] = = Nums[end]) end--;end--;} else if (tmp > Target) end--;elsebegin++;}}} return ans;}}
Java [Leetcode 18]4sum