public class Solution {
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(num==null || num.length <4) return res;
Arrays.sort(num);
// ref http://www.cnblogs.com/springfor/p/3860076.html
HashSet<ArrayList<Integer>> hs= new HashSet<ArrayList<Integer>>();
for(int i=0; i< num.length-3; i++){ // 之前写这两行范围错了,因为下面的要在此基础上加,所以这里要小范围
for(int j=i+1; j< num.length-2; j++){
int low = j+1;
int high = num.length-1;
while(low<high){
int sum = num[i]+num[j]+num[low]+num[high];
if(sum==target){
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(num[i]);
tmp.add(num[j]);
tmp.add(num[low]);
tmp.add(num[high]);
if(!hs.contains(tmp)){
hs.add(tmp);
res.add(tmp);
}
low++;
high--;
}else if(sum<target){
low++;
}else if(sum>target){
high--;
}
}
}
}
return res;
}
}
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(num==null || num.length <4) return res;
Arrays.sort(num);
// ref http://www.cnblogs.com/springfor/p/3860076.html
HashSet<ArrayList<Integer>> hs= new HashSet<ArrayList<Integer>>();
for(int i=0; i< num.length-3; i++){ // 之前写这两行范围错了,因为下面的要在此基础上加,所以这里要小范围
for(int j=i+1; j< num.length-2; j++){
int low = j+1;
int high = num.length-1;
while(low<high){
int sum = num[i]+num[j]+num[low]+num[high];
if(sum==target){
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(num[i]);
tmp.add(num[j]);
tmp.add(num[low]);
tmp.add(num[high]);
if(!hs.contains(tmp)){
hs.add(tmp);
res.add(tmp);
}
low++;
high--;
}else if(sum<target){
low++;
}else if(sum>target){
high--;
}
}
}
}
return res;
}
}