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)
The difference between the solution of this problem and the previous 3sum is that if the previous solution is used, the time complexity becomes O (n^3) so we consider using the hash tale to replace the time with space. The basic approach is to first Hashtable 22 and as key, the corresponding value is the index of the 22 value.
And then traverse time with TARGET-NUM[I]-NUM[J] if the resulting difference is still in the Hashtable, it will be combined into the desired solution. Time complexity O (n^2) space complexity O (n^2) (Here I am still considering because it is 22 selected, so there should be C (n,2))
We can trade space with the 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's still in the Hashtable, we take out the values and make the solution. The overall time and space complexity is 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 (l En (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]: # 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]],n UM[K[1]] Not in solution:solution.append ([num[i],num[j],num[k[0]],num[k[1]]) return s Olution
4Sum Leetcode Python