#
# 
# @param num int整型一维数组 
# @return int整型二维数组
#
class Solution:
    def threeSum(self , num ):
        # write code here
        length = len(num)
        if length <3:
            return []
        res = [] #返回结果
        num.sort() #对数组进行排序
        # 三元组的所有情况有三种:两正一负,两负一正,一负一正一零
        positive = [i for i in num if i >0]
        negative = [i for i in num if i <0]
        zeros = [i for i in num if i ==0]
        #如果只有正数或负数
        if (len(positive) == 0 or len(negative)==0) and len(zeros)<3 :
            return []
        #两负一正的情况
        if len(negative)>1:
            for i in range(len(negative)-1):
                for j in range(i+1,len(negative)):
                    if -(negative[i] + negative[j]) in positive:
                        res.append([negative[i],negative[j],-(negative[i] + negative[j])])
        #一负一正的情况
        if 0 in num and len(negative)>=1 and len(positive)>=1:
            tem = [i for i in positive if -i in negative]
            for i in tem:
                res.append([-i,0,i])
        #三个零的情况:
        if len(zeros)>=3:
            res.append([0,0,0])
        # 两正一负的情况
        if len(positive)>1:
            for i in range(len(positive)-1):
                for j in range(i+1,len(positive)):
                    if -(positive[i] + positive[j]) in negative:
                        res.append([-(positive[i] + positive[j]),positive[i],positive[j]])
        #去重
        new_res = []
        for i in res:
            if i not in new_res:
                new_res.append(i)
        new_res.sort(key = lambda x:x[0])
        return new_res