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
四数之和算法解析

本文探讨了如何寻找数组中四个元素之和等于特定目标值的所有唯一组合,并提供了两种实现方法:一种是通过穷举所有可能的组合,另一种是利用哈希表优化搜索过程。此外,还介绍了Python中用于实现这些算法的相关函数。
799

被折叠的 条评论
为什么被折叠?



