Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)题意:给出一个数组,求所有三个数之和为0的组合
与LeetCode 4Sum(backtrace+剪枝)相似
代码如下:
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>> threeSum(int[] nums)
{
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> arr = new ArrayList<Integer>();
Arrays.sort(nums);
kSum(nums, 0, 3, 0, arr, ans);
return ans;
}
}