class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
return self.nSumTarget(nums,4,0,target)
def nSumTarget(self, nums, n, start,target):
size = len(nums)
res = []
if n<2 or size<n:
return res
if(n==2):
lo = start
high = size-1
while lo<high :
sumData = nums[lo]+nums[high]
left = nums[lo]
right = nums[high]
if sumData<target:
while lo<high and left == nums[lo]:
lo += 1
elif sumData>target:
while lo<high and right == nums[high]:
high -= 1
else:
res.append([left,right])
while lo<high and left == nums[lo]:
lo += 1
while lo<high and right == nums[high]:
high -= 1
else:
for i in range(start,size):
if i>start and nums[i]==nums[i-1]:
continue
ans = self.nSumTarget(nums, n-1, i+1,target-nums[i])
for data in ans:
data.append(nums[i])
res.append(data)
return res
每日一道Leetcode - 18. 四数之和 【递归|nSum】
最新推荐文章于 2024-07-12 19:06:42 发布