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)这道题首先对num数组排序,然后求0~i-1里面加和等于-num[i]的数
因为它要求找唯一的组合,所以需要避免重复
代码来自Code_Ganker
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (num == null || num.length <= 2)
return result;
Arrays.sort(num);
for (int i = num.length - 1; i >= 2; i--) {
if (i < num.length - 1 && num[i] == num[i + 1])
continue;
ArrayList<ArrayList<Integer>> twoRes = twoSum(num, i - 1, -num[i]);
for (int j = 0; j < twoRes.size(); j++)
twoRes.get(j).add(num[i]);
result.addAll(twoRes);
}
return result;
}
public ArrayList<ArrayList<Integer>> twoSum(int[] num, int end, int target) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
int left = 0;
int right = end;
while (left < right) {
if (num[left] + num[right] == target) {
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(num[left]);
temp.add(num[right]);
result.add(temp);
left++;
right--;
while (left < right && num[left] == num[left - 1])
left++;
while (left < right && num[right] == num[right + 1])
right--;
} else if (num[left] + num[right] > target)
right--;
else
left++;
}
return result;
}