题目
Given anarray S of n integers, are thereelements a, b, c, and d in S suchthat a + b + c + d = target? Find allunique quadruplets in the array which gives the sum of target.
Note:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
Asolution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
思路
有了2Sum,3Sum的基础,这道题不难。前面在解决3Sum的时候转化为2Sum来求解,这里同样可以把4Sum转化为3Sum来求解,需要注意的是去除重复结果。
代码
public class Solution {
List<List<Integer>> result =new ArrayList<List<Integer>>();
public List<List<Integer>>fourSum(int[] nums, int target) {
if (nums == null)
return result;
int len = nums.length;
if (len < 4)
return result;
Arrays.sort(nums);
for (int i = 0; i < len - 3; i++) {
if (i > 0 && nums[i] ==nums[i-1])
continue;
threeSum(nums, i + 1, len - 1,target, nums[i]);
}
return result;
}
public void threeSum(int[] nums, int l, intr, int target, int num1) {
for (int i = l; i <= r - 2; i++) {
if (i > l && nums[i] ==nums[i-1])
continue;
twoSum(nums, i + 1, r, target,num1, nums[i]);
}
}
public void twoSum(int[] nums, int l, intr, int target, int num1, int num2){
while (l < r) {
if (num1 + num2 + nums[l] + nums[r]== target) {
List<Integer> list = newArrayList<Integer>();
list.add(num1);
list.add(num2);
list.add(nums[l]);
list.add(nums[r]);
result.add(list);
while (l < r && nums[l] ==nums[l+1])
l++;
while (l < r &&nums[r] == nums[r-1])
r--;
l++;
r--;
}else if (num1 + num2 + nums[l] +nums[r] < target) {
l++;
}else {
r--;
}
}
}
}