4Sum - LeetCode

1431 ワード

4Sum - LeetCode
タイトル:
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:
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)
分析:
この問題は、3 Sum(クリックしてリンクを開く)、3 Sum Closest(クリックしてリンクを開く)の基本原理と同様に、4つの引数があるため、周辺にループを追加する必要があります.コード:
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]