public class Solution { public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) { // the same as 3sum ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if(num==null|| num.length<4) return res; Arrays.sort(num); // 为啥又忘 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, high = num.length-1; while(low<high){ int sum = num[i]+num[j]+num[low]+num[high]; if(sum==target){ // 看见兔子target,才下套 tmp 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 high--; } } } return res; } }