leetcode 018

4 SUMs

ThGiven 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: The solution set must not contain duplicate quadruplets.

Example:

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]
]

Method

Use 2 node moving, and two circulation. The time consuming is N^3

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        Dict = {}
        res = []
        nums.sort()
        for i in range(len(nums)-3):
            for j in range(i + 1,len(nums)-2):
                p = j + 1
                q = len(nums) - 1
                while p != q:
                    s = nums[p] + nums[q] + nums[i] + nums[j]
                    if s == target:
                        if [nums[i],nums[j],nums[p],nums[q]] not in res:
                             res.append([nums[i],nums[j],nums[p],nums[q]])
                    if s > target:
                        q -= 1
                    else:
                        p += 1
        return res