"""
给定一个包含n个整数的数组nums和一个目标值target,判断nums中是否存在四个元素 a,b,c和d
使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
"""defFourSum(nums, target):
n =len(nums)if n<4:return[]
nums.sort()
res =[]for i inrange(n-3):if i >0and nums[i]==nums[i-1]:continueif nums[i]+ nums[i+1]+nums[i+2]+ nums[i+3]> target:breakif nums[i]+ nums[i-1]+ nums[i-2]+ nums[i-3]< target:continuefor j inrange(i+1, n-2):if j-i >1and nums[j]== nums[j-1]:continueif nums[i]+ nums[j]+ nums[j+1]+ nums[j+2]> target:breakif nums[i]+ nums[j]+ nums[j+1]+ nums[j+2]< target:continue
left = j+1
right = n-1while left < right:
temp = nums[i]+ nums[j]+ nums[left]+ nums[right]if temp == target:
res.append([nums[i],nums[j], nums[left], nums[right]])while left < right and nums[left]== nums[left+1]:
left +=1while left < right and nums[right]== nums[right-1]:
right -=1
left +=1
right -=1elif temp > target:
right -=1else:
left +=1return res