A slow Python solution on top of 2 sum.

  • 1
    class Solution(object):
        def threeSum(self, nums):
            res = []
            for i,n in enumerate(nums):
                two = self.twoSum(nums[i + 1:], 0 - n)
                if two:
                    three = [ sorted(x + [n]) for x in two ]
                    for t in three:
                        if t not in res:
                            res += t,
            return res
        def twoSum(self, nums, target):
            got = {}
            res = []
            for n in nums:
                if n not in got:
                    got[target - n] = n
                    res += [got[n], n],
            return res

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.