题目:
Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
such that a + b + c + d = target
? Find all unique quadruplets in the array which gives the sum of target
.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
思路 & 代码:
在列表中不重复地找出和等于目标数的四个数。
将列表用sort()函数由小到大排好序。设置三个变量h, i, j, k,做两层循环,h from 0 to n - 3,i from 0 to n - 2,初始值:j = i + 1,k = n - 1,nums[h]、nums[i]、nums[j]、nums[k]四个数的和sum与target进行比较:若sum == target,创建一个元素为这四个数的列表,并将这个列表添加到存放所有结果的列表里,j += 1,k -= 1,即j、k往中间都挪一步,并检查是否 j < k 以及nums[j]、nums[k]是否与前一个值有异,避免重复;在 j < k 的前提下,sum > target,k -= 1,并检查是否 j < k 以及nums[k]是否与前一个值有异,避免重复,反之,j += 1,并检查是否 j < k 以及nums[j]是否与前一个值有异,避免重复;直至遍历结束。
另. 遍历时除第一次外每次检查 nums[h]、nums[i] 是否与列表中前一个数相同,避免重复工作。
class Solution:def fourSum(self, nums, target):
nums.sort()
#print(nums)
res = []
n = len(nums)
for h in range(n - 3):
#print(h)
if h > 0 and nums[h] == nums[h - 1]:
continue
for i in range(h + 1, n - 2):
if i > h + 1 and nums[i] == nums[i - 1]:
continue
j = i + 1
k = n - 1
while j < k:
#print(i, j, k)
sum = nums[h] + nums[i] + nums[j] + nums[k]
if sum == target:
tmp = [nums[h], nums[i], nums[j], nums[k]]
res.append(tmp)
j += 1
k -= 1
while j < k and nums[j] == nums[j - 1]: j += 1
while j < k and nums[k] == nums[k + 1]: k -= 1
elif sum > target:
k -= 1
while j < k and nums[k] == nums[k + 1]: k -= 1
else:
j += 1
while j < k and nums[j] == nums[j - 1]: j += 1
return res
sol = Solution()
nums = [1, 0, -1, 0, -2, 2]
target = 0
print(sol.fourSum(nums, target))