57. 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. Notice,

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.

Example

``````For example, given array S = {-1 0 1 2 -1 -4}, A solution set is:

(-1, 0, 1)
(-1, -1, 2)
``````

### Python Solutions

``````class Solution:
"""
@param: numbers: Give an array numbers of n integer
@return: Find all unique triplets in the array which gives the sum of zero.
"""
def threeSum(self, numbers):
ret = []
n = len(numbers)
numbers.sort()
for pos in xrange(n - 2):
if pos != 0 and numbers[pos] == numbers[pos - 1]:
continue
i, j = pos + 1, n - 1
while i < j:
if i != pos + 1 and numbers[i] == numbers[i - 1]:
i += 1
continue

if j != n - 1 and numbers[j] == numbers[j + 1]:
j -= 1
continue

if numbers[i] + numbers[j] == -numbers[pos]:
temp = [numbers[pos], numbers[i], numbers[j]]
temp.sort()
ret.append(temp)
i += 1
j -= 1
elif numbers[i] + numbers[j] + numbers[pos] < 0:
i += 1
else:
j -= 1
return ret

# Total Runtime: 454 ms
# 100% test cases passed.

``````