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.
public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 3; i++) { if (i > 0 && nums[i] == nums[i - 1]) continue;
threeSum(nums, target, nums[i], i + 1, result); }
return result;
}
privatevoid(int[] nums, int target, int num, int left, List<List<Integer>> result){ for (int i = left; i < nums.length - 2; i++) { if (i > left && nums[i] == nums[i - 1]) continue;
twoSum(nums, target, num, nums[i], i + 1, result); } }
privatevoidtwoSum(int[] nums, int target, int num1, int num2, int left, List<List<Integer>> result){ int sum = target - num1 - num2; int right = nums.length - 1;
while (left < right) { if (nums[left] + nums[right] == sum) { result.add(Arrays.asList(num1, num2, nums[left], nums[right])); left++; right--;
while (left < right && nums[left] == nums[left - 1]) left++;
近期评论