https://oj.leetcode.com/problems/4sum/
http://www.programcreek.com/2013/02/leetcode-4sum-java/
public class Solution { public List<List<Integer>> fourSum(int[] num, int target) { // Solution A return fourSum_Sort(num, target); } ///////////////////////////////// // Solution A: Sort // // General solution for k-sum private List<List<Integer>> fourSum_Sort(int[] num, int target) { if (num == null || num.length < 4) return Collections.emptyList(); // Invalid input // Sort Arrays.sort(num); int len = num.length; Set<List<Integer>> result = new HashSet<>(); // O(n^3) for (int i = 0 ; i < len ; i ++) { for (int j = i + 1 ; j < len ; j ++) { int m = j + 1; int n = len - 1; while (m < n) { int sum = num[i] + num[j] + num[m] + num[n]; if (sum == target) { // Solution find List<Integer> r = tolist(num[i], num[j], num[m], num[n]); Collections.sort(r); result.add(r); m ++; n --; } else if (sum < target) { m ++; } else { n --; } } } } return new ArrayList<>(result); } private List<Integer> tolist(int... nums) { List<Integer> toReturn = new ArrayList<>(nums.length); for (int i : nums) toReturn.add(i); return toReturn; } }