小编典典

三和算法解决方案

algorithm

原始问题陈述:

给定n个整数的数组S,S中是否有元素a,b,c使得a + b + c = 0?在给出零和的数组中查找所有唯一的三元组。

注意:解决方案集不得包含重复的三胞胎。

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is: [[-1, 0, 1], [-1, -1, 2]]

您好,我前一段时间在LeetCode上解决了“两个和”问题,我想也可以用它来解决三个和。我的想法是,对于每个元素,在剩余的列表中找到两个元素,这些元素的总和为* * -1,得到0。但是,例如,此代码未通过所有测试

Input: [-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6]
Output: [[-4,-2,6],[-4,0,4],[-4,1,3],[-4,2,2]]
Expected: [[-4,-2,6],[-4,0,4],[-4,1,3],[-4,2,2],[-2,-2,4],[-2,0,2]]

我真的不知道怎么了 有人能对我解释这个问题吗?谢谢

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        def twoSum(self, nums, target):
            targ = target
            for index, i in enumerate(nums):
                targ -= i
                if targ in nums[index+1:]:
                    return [nums[index], nums[nums[index+1:].index(targ)+index+1]]
                else:
                    targ = target
            return None
        res = []
        for index, i in enumerate(nums):
            target = i * -1
            num = nums[:index] + nums [index+1:]
            ans = twoSum(self, num, target)
            if ans != None:
                temp = ans + [i]
                temp.sort()
                res.append(temp)
        print(res)
        import itertools
        res.sort()
        res = list(res for res,_ in itertools.groupby(res))
        return res

原始问题:https :
//leetcode.com/problems/3sum/description/

我正在使用的解决方案:https :
//leetcode.com/problems/two-
sum/description/


阅读 320

收藏
2020-07-28

共1个答案

小编典典

使用itertools

import itertools
stuff = [-1, 0, 1, 2, -1, -4]
stuff.sort()
ls = []
for subset in itertools.combinations(stuff, 3):
    if sum(list(subset))==0:
        # first I have sorted the list because of grouping
        # Ex: [-1, 0, 1] and [0, 1, -1] are build with the same element
        # so here is avoiding this.
        if list(subset) not in ls:
            ls.append(list(subset))
print(ls)

输入输出

input : [-1, 0, 1, 2, -1, -4]
output : [[-1, -1, 2], [-1, 0, 1]]
input : [-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6] 
output: [[-4, -2, 6], [-4, 0, 4], [-4, 1, 3], [-4, 2, 2], [-2, -2, 4], [-2, 0, 2]]
2020-07-28