Description
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.
Example
Given array nums = [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]]
解题思路
和3Sum……一样一样一样一样的
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> answer = new ArrayList<List<Integer>>();
Arrays.sort(nums);
int i, j;
int left_point, right_point, new_target, sum;
int length = nums.length;
int a, b, c;
for (i = 0; i < length - 3; i++) {
new_target = target - nums[i];
for(j = i + 1; j < length - 2; j++){
a = nums[j];
if(j > i + 1 && nums[j] == nums[j - 1])
continue;
left_point = j + 1;
right_point = length - 1;
while(left_point < right_point){
b = nums[left_point];
c = nums[right_point];
sum = a + b + c;
if(sum == new_target){
answer.add(Arrays.asList(new Integer[]{nums[i], a, b, c}));
while(left_point < right_point && nums[left_point] == nums[left_point + 1])
left_point ++;
while(left_point < right_point && nums[right_point] == nums[right_point -1])
right_point --;
left_point ++;
right_point --;
}
else if(sum > new_target){
right_point --;
}
else if(sum < new_target){
left_point ++;
}
}
}
}
List<List<Integer>> new_answer = new ArrayList<>(new HashSet<>(answer));
return new_answer;
}
}