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:
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)
#!/usr/bin/python -tt def sum4(num, target): res = [] unique = {} num = sorted(num) for i,x in enumerate(num[:len(num)-3]): for j,y in enumerate(num[:len(num)-2], 1): k,l=j+1,len(num)-1 s = x+y+num[k]+num[l] print x,y,num[k],num[l], s, target if s==target: temp = (x,y,num[k],num[l]) if temp not in unique: res.append(temp) unique.add(temp) k+=1 l-=1 elif s<target: k+=1 else: l-=1 return res if __name__ == "__main__": li = sum4([1,2,3,4], 10); print li