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: The solution set must not contain duplicate quadruplets.

  1. For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
  2. A solution set is:
  3. [
  4. [-1, 0, 0, 1],
  5. [-2, -1, 1, 2],
  6. [-2, 0, 0, 2]
  7. ]

Solution:

  1. public class Solution {
  2. public List<List<Integer>> fourSum(int[] num, int target) {
  3. List<List<Integer>> res = new ArrayList<List<Integer>>();
  4. Set<String> set = new HashSet<String>();
  5. if (num == null || num.length < 4) {
  6. return res;
  7. }
  8. Arrays.sort(num);
  9. int n = num.length;
  10. for (int i = 0; i < n - 3; i++) {
  11. for (int j = i + 1; j < n - 2; j++) {
  12. int m = j + 1;
  13. int k = n - 1;
  14. while (m < k) {
  15. int sum = num[i] + num[j] + num[m] + num[k];
  16. if (sum == target) {
  17. String key = String.format("%d,%d,%d,%d", num[i], num[j], num[m], num[k]);
  18. if (!set.contains(key)) {
  19. set.add(key);
  20. List<Integer> sol = new ArrayList<Integer>();
  21. sol.add(num[i]);
  22. sol.add(num[j]);
  23. sol.add(num[m]);
  24. sol.add(num[k]);
  25. res.add(sol);
  26. }
  27. m++;
  28. k--;
  29. } else if (sum < target) {
  30. m++;
  31. } else {
  32. k--;
  33. }
  34. }
  35. }
  36. }
  37. return res;
  38. }
  39. }

Time complexity: O(n^3)