34 lines
1.0 KiB
Python
34 lines
1.0 KiB
Python
#!/usr/bin/python
|
|
# yigid balaban <fyb@fybx.dev>
|
|
# neetcode 2024
|
|
# 3sum
|
|
|
|
def solution(nums: list[int]) -> list[list[int]]:
|
|
if len(nums) < 3:
|
|
return []
|
|
if len(nums) == 3 and sum(nums) == 0:
|
|
return [nums]
|
|
|
|
nums = sorted(nums)
|
|
triples = []
|
|
def comb(what: list[int], head: int):
|
|
mtriples = []
|
|
for p0 in range(0, len(what) + 1):
|
|
for p1 in range(p0, len(what)):
|
|
if p1 != p0 and head + what[p0] + what[p1] == 0:
|
|
triple = sorted([head, what[p0], what[p1]])
|
|
if triple not in triples and triple not in mtriples:
|
|
mtriples.append(triple)
|
|
return mtriples
|
|
|
|
for p in range(len(nums) - 3):
|
|
triples.extend(comb(nums[p + 1:], nums[p]))
|
|
return triples
|
|
|
|
print(solution([0,0]) == [])
|
|
print(solution([-1,0,1,2,-1,-4]), solution([-1,0,1,2,-1,-4]) == [[-1,-1,2],[-1,0,1]])
|
|
print(solution([0,1,1]) == [])
|
|
print(solution([0,0,0]) == [[0,0,0]])
|
|
print(solution([0,0,0,0]) == [[0,0,0]])
|
|
|