Leetcode solve the problem of 18. 4Sum Java Version (results are four digits of the target value and) __java

Source: Internet
Author: User
4Sum

Given an array s of n integers, are 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: The solution set must not contain duplicate quadruplets.

Give an array, and a target integer, to a,b,c,d and satisfy all the combinations in the array that make and target A<=b<=c<=d

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]
]
reference: 3sum 

Public list<list<integer>> foursum (int[] nums, int target) {list<list<integer>> ret = new Array

		List<> ();
		if (nums = null | | Nums.length < 3) return RET;
		int len = nums.length;
		Arrays.sort (Nums);
		Note that for Num[i], when looking for another two numbers, just start looking from i+1.
		This style of writing avoids repetition in the result set, because the array is ordered,//So when a number is placed in the result set, the following and its equivalent are skipped directly.
			for (int i = 0; i < len; i++) {//Avoid repetition ....
			if (i > 0 && nums[i] = = Nums[i-1]) continue;
				for (int j = i + 1; j < Len; J +) {//Note J if (J > i + 1 && nums[j] = = Nums[j-1]) continue;
				Look backwards, avoid repeating int begin = j + 1;
				int end = Len-1;
					while (begin < end) {int sum = Nums[i] + nums[j] + Nums[begin] + nums[end];
						if (sum = = target) {list<integer> List = new arraylist<> ();
						List.add (Nums[i]);
						List.add (Nums[j]);
						List.add (Nums[begin]);
						List.add (Nums[end]);
						Ret.add (list);
						begin++;
						end--; Avoid duplication。。。。
						while (Begin < end && Nums[begin] = = nums[begin-1]) begin++;
					while (Begin < end && Nums[end] = = nums[end + 1]) end--;
					else if (sum > Target) end--;
				else begin++;
	}} return ret; }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.