#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
18:4sum
https://oj.leetcode.com/problems/4sum/
Given an array S of n integers, is 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 is 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)
===comments by dabay===
The question of K sum can be converted to k-1 sum until 3 sum.
This problem can use space to change the time, with a hash table to record two numbers and the value of their coordinates.
Then two cycles, determine whether there is a hit value in the hash to meet and for target.
If there is, because two cycles are small to large, it should be to meet the size of the hash table smaller coordinates than the internal sequential coordinates.
‘‘‘
Class Solution:
# @return A list of lists of length 4, [[Val1,val2,val3,val4]]
def foursum (self, num, target):
D = {}
Num.sort ()
For i in xrange (Len (num)-1):
For j in Xrange (i+1, Len (num)):
sum2 = Num[i]+num[j]
If sum2 not in D:
D[SUM2] = [[I,j]]
Else
D[sum2].append ([i,j])
res = []
For i in xrange (Len (num)-3):
For j in Xrange (i+1, Len (num)-2):
x = target-(Num[i] + num[j])
If x in D:
for (M,n) in d[x]:
If M > J and [Num[i],num[j],num[m],num[n]] not in res:
Res.append ([num[i],num[j],num[m],num[n]])
return res
def main ():
Sol = solution ()
Nums = [-2,-1, 0, 0, 1, 2]
Print sol.foursum (nums, 0)
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]18:4sum