leetcode 131: 4sum by python

4Sum Jan 27 '12 2865 / 8463

Given an array S of n integers, are there elements abc, 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)


#!/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


你可能感兴趣的:(leetcode 131: 4sum by python)