4Sum - LeetCode

4Sum - LeetCode

题目:

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)

分析:

此题和3Sum(点击打开链接),3Sum Closest(点击打开链接)基本原理一样,区别就在于因为有四个自变量,所以我们需要在外围再加上一个循环。

代码:

class Solution:
    # @return a list of lists of length 4, [[val1,val2,val3,val4]]
    def fourSum(self, num, target):
        if not num or len(num)<4:
            return []
        num.sort()
        res = set()
        for i in range(len(num)-3):
            for j in range(i+1,len(num)-2):
                l = j+1
                h = len(num)-1
                while l < h:
                    if num[l] + num[h] > target - (num[i]+num[j]):
                        h -= 1
                    elif num[l] + num[h] < target - (num[i]+num[j]):
                        l += 1
                    else:
                        res.add((num[i],num[j],num[l],num[h]))
                        l += 1
        return [list(t) for t in res]


你可能感兴趣的:(4Sum - LeetCode)