题目描述:
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)
思路:同3Sum完全一样
public class Four_Sum {
public static ArrayList<int []> fourSum(int array[],int target)
{
ArrayList<int []> result=new ArrayList<int []>();
Arrays.sort(array);
for(int i=0;i<array.length-3;i++)
{
if(i>0&&array[i]==array[i-1])
{
continue;
}
for(int j=i+1;j<array.length-2;j++)
{
if(j>i+1&&array[j]==array[j-1])
{
continue;
}
int start=j+1;
int end=array.length-1;
while(end>start)
{
if(start>j+1&&array[start]==array[start-1])
{
start++;
continue;
}
if(end<array.length-1&&array[end]==array[end+1])
{
end--;
continue;
}
int sum=array[i]+array[j]+array[start]+array[end];
if(sum==target)
{
int num[]=new int[4];
num[0]=array[i];
num[1]=array[j];
num[2]=array[start];
num[3]=array[end];
result.add(num);
start++;
end--;
}
if(sum>target)
{
end--;
}
if(sum<target)
{
start++;
}
}
}
}
return result;
}
public static void main(String[] args) {
int num[]={1,0,-1,0,-2,2,-1,3,-3};
int target=0;
for(int i=0;i<fourSum(num,target).size();i++)
{
for(int j=0;j<fourSum(num,target).get(i).length;j++)
{
System.out.print(fourSum(num,target).get(i)[j]+" ");
}
System.out.print("\n");
}
}
}