首页 > 代码库 > LeetCode:4Sum
LeetCode: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:
- 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)
4Sum问题和3Sum问题没太大区别。
public class Solution {
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
int length = num.length;
String content = "";
if(length < 4) return result;
sort(num,0,length -1);
for(int i = 0;i<length -3;i++)
{
for(int j = i+1;j<length -2;j++)
{
int value = http://www.mamicode.com/target - num[i] - num[j]; > int start = j + 1;
int end = length -1;
while(start < end)
{
if(num[start] + num[end] == value)
{
String temp = "" + num[i] +","+num[j]+","+num[start]+","+num[end]+",";
if(!content.contains(temp))
{
ArrayList<Integer> order = new ArrayList<Integer>();
order.add(num[i]);
order.add(num[j]);
order.add(num[start]);
order.add(num[end]);
content = content + temp;
result.add(order);
}
start ++;
}
else if(num[start] + num[end] > value)
{
end -- ;
}
else if(num[start] + num[end] < value)
{
start ++;
}
}
}
}
return result;
}
public void sort(int[] num,int start,int end)
{
if(start<end)
{
int p = partition(num,start,end);
sort(num,start,p-1);
sort(num,p+1,end);
}
}
public int partition(int[] num,int start,int end)
{
if(end - start==0)return start;
int key = num[start];
while(start<end)
{
while(end>start&&num[end]>key)
{
end -- ;
}
num[start] = num[end];
while(start<end&&num[start]<=key)
{
start ++;
}
num[end] = num[start];
}
num[start]=key;
return start;
}
}