18. 4Sum

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [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]
]

class Solution:
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        nums.sort()
        # print(nums)
        res = set()
        for i in range(len(nums)-3):
            # if i>0 and nums[i]==nums[i-1]:
            #     continue
            if 4*nums[i]>target:
                break
            for j in range(i+1,len(nums)-2):
                # if j>i+1 and nums[j]==nums[j-1]:
                #     continue
                if 3*nums[j]>target - nums[i]:
                    break
                left,right = j+1,len(nums)-1
                # print('i:',i,'j:',j,'left:',left,'right:',right)
                while left<right:
                    ans = nums[i]+nums[j]+nums[left]+nums[right]
                    if ans==target:
                        res.add((nums[i],nums[j],nums[left],nums[right]))
                        left += 1
                        right -= 1
                        continue
                    if ans>target:
                        right -= 1
                        continue
                    if ans<target:
                        left += 1
        return [list(i) for i in res]
posted @ 2018-10-15 10:34  bernieloveslife  阅读(94)  评论(0编辑  收藏  举报