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:
- Elements in a quadruplet (a,b,c,d) must be 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)
代码如下:
1 import java.util.*; 2 public class Solution { 3 public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) { 4 ArrayList<ArrayList<Integer>> all=new ArrayList<ArrayList<Integer>>(); 5 Arrays.sort(num); 6 for(int i=0;i<num.length-3;i++){ 7 if(num[i]+num[i+1]+num[i+2]+num[i+3]>target){ 8 break; 9 } 10 if(num[i]+num[num.length-1]+num[num.length-2]+num[num.length-3]<target){ 11 continue; 12 } 13 int result=target-num[i]; 14 for(int j=i+1;j<num.length-2;j++){ 15 if(num[i]+num[j]+num[j+1]+num[j+2]>target){ 16 break; 17 } 18 if(num[i]+num[num.length-1]+num[num.length-2]+num[j]<target){ 19 continue; 20 } 21 int result2=result-num[j]; 22 int left=j+1,right=num.length-1; 23 while(left<right){ 24 int sum=num[left]+num[right]; 25 if(sum<result2){ 26 left++; 27 }else if(sum>result2){ 28 right--; 29 }else{ 30 ArrayList<Integer> list=new ArrayList<Integer>(); 31 list.add(num[i]); 32 list.add(num[j]); 33 list.add(num[left]); 34 list.add(num[right]); 35 if(!all.contains(list)){ 36 all.add(list); 37 } 38 right--; 39 } 40 } 41 } 42 } 43 return all; 44 } 45 } 46 参考:https://www.nowcoder.com/profile/9319545/codeBookDetail?submissionId=24444004
https://www.cnblogs.com/grandyang/p/4130379.html
浙公网安备 33010602011771号