Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
For example, given array S = {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)
思路:
土一点的解法就是一个一个判断,让四个加起来的和等于target。。然而这样太土了,python表示又TLE啦~~~
class Solution(object):
def fourSum(self, nums, target):
ans=[]
if len(nums)>=4:
for i in range(len(nums)-4):
for j in range(i+1,len(nums)):
for k in range(j+1,len(nums)):
for l in range(k+1,len(nums)):
if nums[i]+nums[j]+nums[k]+nums[l]==target:
temp=sorted([nums[i],nums[j],nums[k],nums[l]])
if temp not in ans:
ans.append(temp)
return ans
好看一点的解法就是,两两求和,存在一个字典里面,key=两数之和,其value存储了该数的对应下标。
用到的函数
enumeration()可以遍历数组,以及返回其下标
for i in enumerate([5,7]):
print i
(0,5)(1,7)
itertools.combinations( XX ,2)函数
随机取两个数且不重复
即ab,ba视为aba=isdisjoin(b):a元素和b元素的交集为空集,则返回为True
python代码:
import collections
import itertools
class Solution:
def fourSum(self,nums,target):
doc=collections.defaultdict(list)
ans=[]
for (id1,val1),(id2,val2) in itertools.combinations(enumerate(nums),2):
doc[val1+val2].append({id1,id2})
keys=doc.keys()
for key in keys:
if doc[key] and doc[target-key]:
for part1 in doc[key]:
for part2 in doc[target-key]:
if part1.isdisjoint(part2):
temp=sorted([nums[i] for i in part1 | part2])
if temp not in ans:
ans.append(temp)
del doc[key]
if key!=target-key:
del doc[target-key]
return ans