给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。
样例
例1:
输入:[2,7,11,15]
输出:[]
例2:
输入:[-1,0,1,2,-1,-4]
输出:[[-1, 0, 1],[-1, -1, 2]]
注意事项
在三元组(a, b, c),要求a <= b <= c。
结果不能包含重复的三元组。
输入测试数据 (每行一个参数)如何理解测试数据?
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.
"""
'''
大致思路:
1.给出所有的三元组组合,然后判断是否sum为0,如果是写入res里面
'''
def threeSum(self, numbers):
res = []
d = []
numbers.sort()
for i in range(len(numbers)):
if i == 0:
d.append([numbers[i]])
else:
for j in range(len(d)):
a = d[j] + [numbers[i]]
d.append(a)
if len(a) == 3 and sum(a) == 0 and a not in res:
res.append(a)
d.append([numbers[i]])
return res
class Solution:
def threeSum(self, numbers):
res = []
numbers.sort()
for i in range(len(numbers)-1):
for j in range(i+1,len(numbers)):
s = -(numbers[i] + numbers[j])
if s in numbers and s >= numbers[j]:
if s == numbers[j] and numbers.count(s) < 2:
continue
a = [numbers[i],numbers[j],s]
if a not in res:
res.append(a)
if [0,0,0] in res:
if numbers.count(0) < 3:
res.remove([0,0,0])
return res