class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
n=len(nums)
#异常处理
if n < 4:
return []
res=[]
#排序
nums=sorted(nums)
for i in range(n):
#a+b+c+d=nums[i]+nums[j]+nums[left]+nums[right]=target
#异常处理,减枝
if nums[i] > target and (nums[i]>=0 or target>=0):
break
#a去重
if i>0 and nums[i]==nums[i-1]:
continue
for j in range(i+1,n):
left=j+1
right=n-1
#b去重
if j > i+1 and nums[j]==nums[j-1]:
continue
while left < right:
sum=nums[i]+nums[j]+nums[left]+nums[right]
if sum > target:
right-=1
elif sum < target:
left+=1
else:
res.append([nums[i],nums[j],nums[left],nums[right]])
#去重c和d
while left < right and nums[left]==nums[left+1]:
left+=1
while left < right and nums[right]==nums[right-1]:
right-=1
#左右指针移位
left+=1
right-=1
return res