15. 3Sum

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: The solution set must not contain duplicate triplets.

1
2
3
4
5
6
7
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

解法1: Backtracking

典型的backtracking + 去重的问题。
主要的容易错的地方是怎么去重,当确定了其中一个数字的位置i之后,在变动left和right时,每当找到一个满足条件的解都要跳过之后所有和left或者right指向的相同的数字。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
if (i != 0 && nums[i] == nums[i -1]) continue;
int left = i + 1, right = nums.length - 1;
while (left < right) {
if (nums[i] + nums[left] + nums[right] == 0) {
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[left]);
temp.add(nums[right]);
res.add(temp);
left++;
right--;
while (left < right && nums[left - 1] == nums[left]) left++;
while (left < right && nums[right + 1] == nums[right]) right--;
} else if (nums[i] + nums[left] + nums[right] < 0) {
left++;
} else {
right--;
}
}
}
return res;
}
}