Leetcode上有2Sum,3Sum等问题,基本思路都是一样的,从3Sum开始,固定其他数,剩下两个数变成2Sum问题。2Sum问题在排序数组里用首尾两个游标遍历
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
n=sorted(nums)
ans=[]
for i in range(len(n)):
for j in range(i+1,len(n)):
now=target-n[i]-n[j]
s=j+1
e=len(n)-1
if s>=e:
continue
while s<e:
tmp=n[s]+n[e]
if tmp<now:
s+=1
elif tmp>now:
e=e-1
else:
aa=[n[i],n[j],n[s],n[e]]
if aa not in ans:
ans.append(aa)
s=s+1
e=e-1
return ans