LeetCode Medium: 18. 4Sum

一、题目

Given an array nums of n integers and an integer target, are there elements abc, 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]
]
给定一个Array和一个target,在Array中选取4个数,使其相加等于target,返回所有的list集合。

 二、思路

与前面的3sum一样,先排序,然后可以先固定两个,两两组合,生成一个字典,然后再遍历循环,解决问题。

三、代码

#coding:utf-8
def fourSum(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[List[int]]
    """
    nums = sorted(nums)
    if len(nums) < 4:
        return []
    list_sums = set()
    dict = {}
    for point in range(len(nums)):
        for nextpoint in range(point + 1, len(nums)):
            if nums[point] + nums[nextpoint] not in dict:
                dict[nums[point] + nums[nextpoint]] = [(point, nextpoint)]
            else:
                dict[nums[point] + nums[nextpoint]].append((point, nextpoint))
    for i in range(len(nums)):
        for j in range(i + 1, len(nums) - 2):
            target_remain = target - nums[i] - nums[j]
            if target_remain in dict:
                for k in dict[target_remain]:
                    if k[0] > j:
                        list_sums.add((nums[i], nums[j], nums[k[0]], nums[k[1]]))
    return [list(i) for i in list_sums]

参考博客:https://blog.csdn.net/NXHYD/article/details/72514823

猜你喜欢

转载自www.cnblogs.com/xiaodongsuibi/p/8862195.html
今日推荐