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)题意:给出一个数组,求由4个数组成的和为0的所有组合
思路:回溯法,在回溯时注意剪枝
(1)剩余的可取区间中,如果第一个元素的连续和大于目标值或者最后一个元素的连续和小于目标值,递归不继续
(2)在剩余的可取区间中,如果后续的取值与上次相同,不继续
(3)在剩余层次为2层时,根据与目标值的关系来决定区间的起始值和结束值
代码如下:
class Solution {
private void kSum(int[] nums, int start, int k, int target, List<Integer> arr, List<List<Integer>> ans)
{
int len = nums.length;
if (start >= len || 0 == k) return;
if (1 == k)
{
for (int i = start; i < len; i++)
{
if (nums[i] == target)
{
arr.add(nums[i]);
ans.add(new ArrayList<Integer>(arr));
arr.remove(arr.size() - 1);
}
}
return;
}
if (2 == k)
{
int end = len - 1;
while (start < end)
{
int sum = nums[start] + nums[end];
if (sum == target)
{
arr.add(nums[start]);
arr.add(nums[end]);
ans.add(new ArrayList<Integer>(arr));
arr.remove(arr.size() - 1);
arr.remove(arr.size() - 1);
while (start < end && nums[start] == nums[start + 1]) start++;
start++;
while (start < end && nums[end] == nums[end - 1]) --end;
--end;
}
else if (sum < target)
{
while (start < end && nums[start] == nums[start + 1]) start++;
start++;
}
else
{
while (start < end && nums[end] == nums[end - 1]) end--;
end--;
}
}
return;
}
if (k * nums[start] > target || k * nums[len - 1] < target) return;
for (int i = start; i <= (len - k); i++)
{
if (i > start && nums[i] == nums[i - 1]) continue;
if (k * nums[i] <= target)
{
arr.add(nums[i]);
kSum(nums, i + 1, k - 1, target - nums[i], arr, ans);
arr.remove(arr.size() - 1);
}
}
}
public List<List<Integer>> fourSum(int[] nums, int target)
{
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> arr = new ArrayList<Integer>();
Arrays.sort(nums);
kSum(nums, 0, 4, target, arr, ans);
return ans;
}
}