一、使用2sum降低复杂度为O(N^2)
1 public class Solution { 2 public List
> fourSum(int[] nums, int target) { 3 Arrays.sort(nums); 4 List
> res = new LinkedList
>(); 5 for(int i=0;i listone = new LinkedList ();16 listone.add(nums[i]);17 listone.add(nums[j]);18 listone.add(nums[left]);19 listone.add(nums[right]);20 res.add(listone);21 left++;22 right--;23 while(left
二、和3Sum是一样的,只是多了一层循环而已。
1 public class Solution { 2 public List
> fourSum(int[] nums, int target) { 3 Arrays.sort(nums); 4 List
> listall = new LinkedList
>(); 5 for(int i=0;i 0&&num1==nums[i-1]) continue; 8 for(int j=i+1;j i+1&&num2==nums[j-1]) continue;11 for(int k=j+1;k j+1&&num3==nums[k-1]) continue;14 for(int m=k+1;m k+1&&num4==nums[m-1]) continue;17 int sum=num1+num2+num3+num4;18 if(sum==target){19 List listone = new LinkedList ();20 listone.add(num1);21 listone.add(num2);22 listone.add(num3);23 listone.add(num4);24 listall.add(listone);25 }26 if(sum>target)27 break;28 }29 }30 }31 }32 return listall;33 }34 }