18. 4Sum

Given an array S of n integers, are there elements abc, 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.

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]
]
题目含义:从数组中找4个数字,使得加和等于目标值target,找出所有的组合

 1   public List<List<Integer>> threeSum(int[] nums, int target, int firstNumber) {
 2         List<List<Integer>> res = new LinkedList<>();
 3         for (int i = 0; i < nums.length; i++) {
 4             if (i > 0 && nums[i] == nums[i - 1]) continue;
 5             int low = i + 1, high = nums.length - 1;
 6             while (low < high) {
 7                 if (nums[i] + nums[low] + nums[high] == target) {
 8                     res.add(Arrays.asList(firstNumber, nums[i], nums[low], nums[high]));
 9                     while (low < high && nums[low] == nums[low + 1]) low++;
10                     while (low < high && nums[high] == nums[high - 1]) high--;
11                     low++;
12                     high--;
13                 } else if (nums[i] + nums[low] + nums[high] > target) high--;
14                 else low++;
15             }
16         }
17         return res;
18     }
20 
21     public List<List<Integer>> fourSum(int[] nums, int target) {
22         Arrays.sort(nums);
23         List<List<Integer>> res = new LinkedList<>();
24         if (nums.length == 0) return res;
25         for (int i = 0; i < nums.length; i++) {
26             if (i > 0 && nums[i] == nums[i - 1]) continue;
27             int[] rightNums = Arrays.copyOfRange(nums, i+1, nums.length);
28             List<List<Integer>> threeSum = threeSum(rightNums, target - nums[i], nums[i]);
29             res.addAll(threeSum);
30         }
31         return res;
32     }

 

 类似题目:15. 3Sum

posted @ 2017-10-25 20:15  daniel456  阅读(420)  评论(0编辑  收藏  举报