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]
]
# 思路比较简单,在三个数求和的基础上进行迭代。
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
nums_length = len(nums)
if nums_length<4: return res
nums = sorted(nums)
for i in range(nums_length-3):
if i>0 and nums[i-1]==nums[i]:
continue
nums_tmp = nums[i+1:]
r = self.threeSum(nums_tmp, target-nums[i])
for per_r in r:
per_r.insert(0,nums[i])
res.append(per_r)
return res
def threeSum(self, nums, target):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums = sorted(nums)
nums_length = len(nums)
for i in range(nums_length-2):
if i>0 and nums[i-1]==nums[i]:
continue
a = nums[i]
low = i + 1
high = nums_length - 1
while (low < high):
b = nums[low]
c = nums[high]
if a+b+c==target:
res.append([a,b,c])
while(low<nums_length-1 and nums[low]==nums[low+1]):
low += 1
while(high>0 and nums[high]==nums[high-1]):
high -= 1
low += 1
high -= 1
elif (a+b+c)>target:
while(high>0 and nums[high]==nums[high-1]):
high -= 1
high -= 1
else:
while(low<nums_length-1 and nums[low]==nums[low+1]):
low += 1
low += 1
return res