这道题目使用了nSum的递归思想来解决。首先将数组排序,然后递归地调用nSum函数,将问题不断分解成更小的子问题,直到问题简化为两数之和。在两数之和的处理中,使用双指针技巧来寻找和为目标值的元素对。为了避免重复解,每次找到一个解后,需要跳过相同的元素。
时间复杂度: O(n^3)
空间复杂度: O(n^3)
from typing import List
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
def nSum(n, start, tar):
res = []
if n == 2:
i = start
j = len(nums)-1
while i < j:
s = nums[i] + nums[j]
left = nums[i]
right = nums[j]
if s < tar:
while i < j and nums[i] == left:
i += 1
elif s > tar:
while i < j and nums[j] == right:
j -= 1
else:
res.append([left, right])
while i < j and nums[i] == left:
i += 1
while i < j and nums[j] == right:
j -= 1
elif n > 2:
i = start
while i < len(nums):
tuples = nSum(n-1, i+1, tar-nums[i])
for t in tuples:
t.append(nums[i])
res.append(t)
while i+1 < len(nums) and nums[i+1] == nums[i]:
i += 1
i += 1
return res
nums.sort()
return nSum(4, 0, target)
if __name__ == '__main__':
s = Solution()
print(s.fourSum([-2,-1,-1,1,1,2,2], 4))