(-2, 0, 0, 2)
这题的解法和前面3sum的区别在于如果采用之前的解法,时间复杂度变为O(n^3) 因此我们考虑采用hash tale来用空间换时间。 基本做法是先把两两的和作为key存在hashtable,对应的 value是两两值的index.
然后再遍历时候用target -num[i]-num[j] 如果得到的差值还在hashtable里面就将其组合成所要的解。 时间复杂度为O(n^2) 空间复杂度为O (n^2)(这里我还在考虑因为是两两选出来,所以应该有C(n,2)个)
We can trade space with time in this problem. first iterate the num and use 2 sum as the key ,indexes as the value in hastable.
Then we start iterate again. take target -num[i]-num[j],if it is still in the hashtable, we take out the values and make the solution. The overall time and space complexity are both O(n^2)
code:
class Solution:
# @return a list of lists of length 4, [[val1,val2,val3,val4]]
def fourSum(self, num, target):
solution=[]
num.sort()
dict={}
if len(num)<4:
return solution
for i in range(len(num)):
#if i>0 and num[i]==num[i+1]:
# continue
for j in range(i+1,len(num)):
val=num[i]+num[j]
if val not in dict:
dict[val]=[[i,j]]
else:
dict[val].append([i,j])
for i in range(len(num)):
# if i>0 and num[i]==num[i+1]:## we should delete this here
# continue
for j in range(i+1,len(num)-2):
dif=target-num[i]-num[j]
if dif in dict:
for k in dict[dif]:
if k[0]>j and [num[i],num[j],num[k[0]],num[k[1]]] not in solution:
solution.append([num[i],num[j],num[k[0]],num[k[1]]])
return solution