Original Problem Statement:
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.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is: [[-1, 0, 1], [-1, -1, 2]]
I solved the Two Sum problem on LeetCode some time back and I thought of using it to solve the three sum as well. My idea is that for every element find two elements in the remaining list which sum up to element * -1 to get 0. However, this code doesn't pass all the test, for example
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]]
I don't really know what's wrong. Can someone be kind enough to explain the problem to me.
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
Original Question: https://leetcode.com/problems/3sum/description/
The one I'm using to solve this: https://leetcode.com/problems/two-sum/description/
See Question&Answers more detail:
os