其思路类似于3sum。下面是题目和代码。
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:
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. A solution set is: (-1, 0, 0, 1) (-2, -1, 1, 2) (-2, 0, 0, 2)
import java.util.*;
public class Solution {
public List> fourSum(int[] nums, int target) {
List> result = new ArrayList<>();
if (nums == null || nums.length < 4) return result;
Arrays.sort(nums);
int len = nums.length;
for (int i = 0; i < len - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue; // Skip same results
for (int j = i + 1; j < len - 2; j++) {
if (j > 1 && i != j - 1 && nums[j] == nums[j - 1]) continue;
int target2 = target - nums[i] - nums[j];
int k = j + 1, l = len - 1;
while (k < l) {
if (nums[k] + nums[l] == target2) {
result.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
while (k < l && nums[k] == nums[k + 1]) k++; // Skip same results
while (k < l && nums[l] == nums[l - 1]) l--; // Skip same results
k++;
l--;
} else if (nums[k] + nums[l] < target2) {
k++;
} else {
l--;
}
}
}
}
return result;
}
public static void main(String[] args) {
int[] nums = new int[] {2,1,0,-1};
int target = 2;
List> result;
Solution solution = new Solution();
result = solution.fourSum(nums, target);
for (List l: result) {
for (int i = 0; i < l.size(); i++) {
System.out.print(l.get(i));
if (i != l.size() - 1) {
System.out.print("+");
}
}
System.out.println("="+ target);
}
}
}