2017.9.25
四数之和其实可以转化为三数之和。
对于数组中的每一个数,可以转化为 求解 threeSum(num[i], target - num[i])
public class Solution {
/*
* @param numbers: Give an array
* @param target: An integer
* @return: Find all unique quadruplets in the array which gives the sum of zero
*/
public static List<List<Integer>> fourSum(int[] numbers, int target) {
// write your code here
List<List<Integer>> res = new LinkedList<>();
int length = numbers.length;
if(length <= 3){
return res;
}
Arrays.sort(numbers);
for(int i = 0 ; i < length ; i++){
int []num = new int[length-1-i];
num = Arrays.copyOfRange(numbers, i+1, length);
List<List<Integer>> list = new LinkedList<>();
list = threeSum(num,target-numbers[i]);
for(int k = 0; k < list.size();k++){
List<Integer> tmp = new LinkedList<>();
List<Integer> tmp1 = list.get(k);
tmp.add(numbers[i]);
tmp.addAll(tmp1);
res.add(tmp);
}
while(i < length-1 && numbers[i] == numbers[i+1]){
i++;
}
}
return res;
}
public static List<List<Integer>> threeSum(int[] numbers, int target) {
// write your code here
List<List<Integer>> res = new LinkedList<>();
Arrays.sort(numbers);
int length = numbers.length;
if(length <=2){
return res;
}
for(int i = 0 ; i < length;i++){
// 这里是为了跳过重复的元素
for(int j = i+1; j < length; j++){
for(int h = j+1; h < length; h++){
if(h != length -1 && numbers[h] == numbers[h+1]){
continue;
}
if(numbers[j] + numbers[h] + numbers[i] == target){
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(numbers[i]);
list.add(numbers[j]);
list.add(numbers[h]);
if(res.contains(list)){
continue;
}
res.add(list);
}
while(h != length -1 && numbers[h] == numbers[h+1]){
h++;
}
}
while(j != length -1 && numbers[j] == numbers[j+1]){
j++;
}
}
while(i != length-1 && numbers[i] == numbers[i+1]){
i++;
}
}
return res;
}
}